<?php
/**
 * 帮你跑腿用户端接口控制器
 * 2016年06月28日09:42:00
 */
namespace Api\Controller;

use Common\Controller\HomebaseController;
use Alidayu\AlidayuClient as Client;
use Alidayu\Request\SmsNumSend;


class V1Controller extends HomebaseController
{
    protected $order;


    function _initialize()
    {
        parent::_initialize();
        $this->order = D("Order");
    }

    /**
     * @api {get} userLogin/mobile/:mobile/validate_code/:validate_code/ 用户登录
     * @apiGroup pt
     * @apiName 用户登录
     *
     * @apiParam {Int} mobile 用户手机号.
     * @apiParam {Int} validate_code 短信验证v码.
     **/
    function userLogin()
    {
        $mobile = I("mobile");
        $validate_code = I("validate_code", 0, 'intval');
        //为了苹果审核且不影响正常业务
        if ($mobile == 18538512653 && $validate_code == 1234) {
            $return = $this->loginReturn(18538512653);//登录返回数据
            return RET(0, "登录成功", $return);
        } else {
            if ($validate_code == session('code')) {
                if (!$mobile || !$validate_code) {
                    return RET_NO_V(2, "手机号或验证码未填写");
                }

                $app_users = M("app_users");
                $retx = $app_users->where(array('mobile' => $mobile))->field('mobile,user_id,account_status,freeze_reason,first_login_time')->find();
                if ($retx) {//此用户已经存在
//            return RET_NO_V(3, "此用户已经存在！");
                    if (0 == $retx['account_status']) {
                        return RET_NO_V(1, "您账号已被冻结，请联系客服！");
                    }
                    $app_users->startTrans();

                    //========第一次登陆的时间 start=============
                    $first_login_time = $retx['first_login_time'];
                    if (!$first_login_time)
                        $first_login_time = date('Y-m-d H:i:s', time());
                    //========== 第一次登陆的时间end =================
                    //修改token
                    $rets = $app_users->where(array('mobile' => $mobile))->save(array('validate_code' => $validate_code, 'token' => md5(uniqid(rand())), 'last_login_time' => date('Y-m-d H:i:s', time()), 'first_login_time' => $first_login_time));

                    if ($rets) {
                        //推荐关系表
                        $recommend = M('recommend');
                        //获取推荐表此人是否是未激活状态
                        $recommend_status = $recommend->where(array('recommended_person_id' => $retx['user_id'], 'recommended_person_type' => 1, 'recommended_status' => 0))->field('recommend_id,recommended_status,recom_person_id,recom_person_type,recommended_person_id')->find();
                        //如果为推荐的人
                        if ($recommend_status) {//没激活
                            $ret = $recommend->where(array('recommend_id' => $recommend_status['recommend_id']))->save(array('recommended_status' => 1));
                            if ($ret) {//有推荐人
                                //推荐成功发消息
                                if ($recommend_status['recom_person_type'] == 1) {
                                    $msg_ret = create_user_message($recommend_status['recom_person_id'], '推荐用户注册登录成功', '恭喜您！推荐用户注册登录成功', '恭喜您！推荐用户注册登录成功');
                                    if (!$msg_ret) {//调用方法，返回  0失败 roll，其他值不管
                                        $app_users->rollback();
                                        return RET_NO_V(1, "给此用户的推荐人发消息失败，请稍后再试");
                                    }
                                } elseif ($recommend_status['recom_person_type'] == 2) {
                                    $msg_ret = create_dispatch_message($recommend_status['recom_person_id'], '推荐用户注册登录成功', '恭喜您！推荐用户注册登录成功', '恭喜您！推荐用户注册登录成功');
                                    if (!$msg_ret) {//调用方法，返回  0失败 roll，其他值不管
                                        $app_users->rollback();
                                        return RET_NO_V(1, "给此用户的推荐人发消息失败，请稍后再试");
                                    }
                                }

                                //新用户奖励优惠券
                                $coupon_ret = newuser_reward_coupon2($retx['user_id'], 'xyhyh');
                                if (1 == $coupon_ret) {
                                    //优惠券发放成功发消息
                                    $coupon_info = M("coupon_info");
                                    $cou_ret = $coupon_info->field('coupon_value')->where("coupon_key='xyhyh' and is_push=1 and surplus_num >0")->find();
                                    $msg_ret = create_user_message($retx['user_id'], '新用户注册登录成功有礼', '新用户注册登录成功赠送优惠券', '新用户注册登录成功赠送' . $cou_ret['coupon_value'] . '元优惠券');
                                    if (!$msg_ret || !$cou_ret) {//调用方法，返回  0失败 roll，其他值不管
                                        $app_users->rollback();
                                        return RET_NO_V(1, "新用户优惠券发放系统消息插入有误，请稍后再试");
                                    }
                                } elseif (!$coupon_ret) {//调用方法，返回  0失败 roll，其他值不管
                                    $app_users->rollback();
                                    return RET_NO_V(1, "新用户领优惠券有误，请稍后再试");
                                }

                                //=============新用户注册成功--随机奖励推荐人；用户1~3元优惠券，跑客1-2元余额============
//                                if ($recommend_status['recom_person_type'] == 1) {//推荐人是用户,被推荐人是用户的，给推荐人发优惠券，被推荐人是跑客的，不发优惠券
//                                    $rand = rand(1, 2);
//
//                                    if ($rand == 1)
//                                        $rand_key = 'S7Rz6VbZHeNy7NrB';
//                                    else if ($rand == 2)
//                                        $rand_key = 'ecnnL%Oywj7#j6X!';
//                                    //else if($rand == 3)
//                                    //    $rand_key = '19^T6QsQneyES@w9';
//
//                                    $rand_ret = newuser_reward_coupon2($recommend_status['recom_person_id'], $rand_key, $recommend_status['recommended_person_id']);//奖励推荐人优惠券
//
//                                    if (1 == $rand_ret) {
//                                        //优惠券发放成功发消息
//                                        $coupon_info = M("coupon_info");
//                                        $cou_ret1 = $coupon_info->field('coupon_value')->where("coupon_key='" . $rand_key . "' and is_push=1 and surplus_num >=0")->find();
//                                        $user_msg_ret = create_user_message($recommend_status['recom_person_id'], '推荐新用户注册登录成功有礼', '随机奖励' . $rand . '元优惠券已发放给您', '随机奖励' . $rand . '元优惠券已发放给您');
//
//                                        if (1 == $user_msg_ret && $cou_ret1) {//调用方法，返回  1成功 commit 0失败 roll，其他值不管
//                                            $return = $this->loginReturn($mobile);
//                                            $upmsg_ret = login_upmsg_sys($retx['user_id'], 1);//用户系统消息表
//                                            $app_users->commit();
//                                            return RET(0, "登录成功", $return);
//                                        } elseif (!$user_msg_ret) {//调用方法，返回  0失败 roll，其他值不管
//                                            $app_users->rollback();
//                                            return RET_NO_V(1, "推荐有误，请稍后再试");
//                                        }
//                                    } elseif (!$rand_ret) {//调用方法，返回  0失败 roll，其他值不管
//                                        $app_users->rollback();
//                                        return RET_NO_V(1, "推荐有误，请稍后再试");
//                                    }
//
//                                } elseif ($recommend_status['recom_person_type'] == 2) {//推荐人是跑客，奖励1-2元余额
//                                    $rand = rand(1, 2);
//                                    //增加余额，增加推荐奖励金额
//                                    $user_db = M('dispatch');
//                                    $user_purse = $user_db->where(' dispatch_id = ' . $recommend_status['recom_person_id'])->field('cash_balance,recommend_amount')->find();
//                                    $cash_balance = floatval($user_purse['cash_balance']) + $rand;//推荐人的账户金额
//                                    $recommen_count = floatval($user_purse['recommend_amount']) + $rand;//推荐人的推荐金额
//                                    $dispatch_ret = $user_db->where('dispatch_id=' . $recommend_status['recom_person_id'])->setField(array('recommend_amount' => $recommen_count, 'cash_balance' => $cash_balance));
//
//                                    //跑客钱包表
//                                    $balance_ret = create_dispatch_balance($recommend_status['recom_person_id'], 5, $rand, 0, '推荐新用户注册登录成功，随机奖励' . $rand . '元');
//                                    //发送推荐奖励消息
//                                    $dismsg_ret = create_dispatch_message($recommend_status['recom_person_id'], '推荐新用户注册登录成功有礼', '随机奖励' . $rand . '元已存入您的账户', '随机奖励' . $rand . '元已存入您的账户');
//                                    if ($dispatch_ret && $balance_ret && $dismsg_ret) {
//                                        $return = $this->loginReturn($mobile);
//                                        $upmsg_ret = login_upmsg_sys($retx['user_id'], 1);//用户系统消息表
//                                        $app_users->commit();
//                                        return RET(0, "登录成功", $return);
//                                    } else {
//                                        $app_users->rollback();
//                                        return RET_NO_V(1, "推荐有误，请稍后再试");
//                                    }
//                                }
                                $upmsg_ret = login_upmsg_sys($retx['user_id'], 1);//用户系统消息表
                                $app_users->commit();
                                $return = $this->loginReturn($mobile);
                                return RET(0, "登录成功", $return);
                            } else {// add/save，返回  成功comit，失败roll
                                $app_users->rollback();
                                return RET_NO_V(1, "激活状态变更有误，请稍后再试");
                            }
                        }
                        $upmsg_ret = login_upmsg_sys($retx['user_id'], 1);//用户系统消息表
                        $app_users->commit();
                        $return = $this->loginReturn($mobile);
                        return RET(0, "登录成功", $return);
                    } else {
                        $app_users->rollback();
                        return RET_NO_V(1, "登录失败，请稍后再试");
                    }
                } else {
                    $app_users->startTrans();
                    $coupon_info = M("coupon_info");
                    //此用户已经不存在
                    $ret = $app_users->add(array('mobile' => $mobile, 'user_name' => $mobile, 'avatar' => 'Uploads/public/icon.png', 'account_status' => 1, 'purse_balance' => 0.00, 'user_level_id' => 1, 'growth_value' => 10, 'validate_code' => $validate_code, 'token' => md5(uniqid(rand())), 'regist_time' => date('Y-m-d H:i:s', time()), 'is_shop' => 0, 'first_login_time' => date('Y-m-d H:i:s', time()), 'last_login_time' => date('Y-m-d H:i:s', time())));//注册
                    if ($ret) {//注册成功，允许登录系统
                        $coupon_ret = newuser_reward_coupon2($ret, 'xyhyh');
                        $cou_ret = $coupon_info->field('coupon_value')->where("coupon_key='xyhyh' and is_push=1 and surplus_num >0")->find();

                        if (1 == $coupon_ret && $cou_ret) {//调用方法，返回  1成功 commit 0失败 roll，其他值不管
                            $msg_ret = create_user_message($ret, '新用户注册登录有礼', '新用户注册登录赠送优惠券', "新用户登录赠送" . $cou_ret['coupon_value'] . "元优惠券");
                            if (1 == $msg_ret) {//调用方法，返回  1成功 commit 0失败 roll，其他值不管
                                $return = $this->loginReturn($mobile);
//                        $upmsg_ret = login_upmsg_sys($ret,1);//更新老用户系统消息 信息
                                $app_users->commit();
                                return RET(0, "登录成功", $return);
                            } elseif (!$msg_ret) {//调用方法，返回  1成功 commit 0失败 roll，其他值不管
                                $app_users->rollback();
                                return RET_NO_V(1, "新用户优惠券发放系统消息插入有误，请稍后再试");
                            }
                        } elseif (!$coupon_ret) {//调用方法，返回  1成功 commit 0失败 roll，其他值不管
                            $app_users->rollback();
                            return RET_NO_V(1, "新用户领优惠券有误，请稍后再试");
                        }
                        $upmsg_ret = login_upmsg_sys($ret, 1);//更新老用户系统消息 信息
                        $app_users->commit();
                        $return = $this->loginReturn($mobile);//登录返回数据
                        return RET(0, "登录成功", $return);
                    } else {//注册失败
                        $app_users->rollback();
                        return RET_NO_V(1, "登录失败，请稍后再试");
                    }
                }

            } else {
                return RET_NO_V(3, "抱歉验证码错误!");
            }
        }
    }


    //登录返回数据
    protected function loginReturn($mobile)
    {
        $app_users = M("app_users");
        $return = $app_users->where(array('mobile' => $mobile))->find();
        $level = M('user_level')->where(array('user_level_id' => $return['user_level_id']))->field('level_name,level_img')->find();
        $return['level_name'] = $level['level_name'];//用户级别名称
        $return['level_img'] = $level['level_img'];//用户级别图标
        return $return;
    }


    /**
     * @api {get} userPosition/token/:token/uid/:uid/latitude/:latitude/longitude/:longitude 用户位置更新
     * @apiGroup pt
     * @apiName 用户位置更新(10秒更新一次)
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {string} latitude 纬度.
     * @apiParam {string} longitude 经度.
     **/
    function userPosition()
    {
        //校验token
        verificationToken();
        $app_users = M("app_users");
        $ret = $app_users->where(array('user_id' => I('uid')))->save(array('latitude' => I("latitude"), 'longitude' => I("longitude"), 'place_up_time' => date('Y-m-d H:i:s', time())));
        if ($ret) {
            return RET_NO_V(0, "用户位置更新成功！");
        } else {
            return RET_NO_V(1, "用户位置更新失败");
        }
    }

    /**
     * @api {get} getUserSet/token/:token/uid/:uid 获取用户设置
     * @apiName 判断当前用户是否有设置如果没有则初始化
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     **/
    function getUserSet()
    {
        //校验token
        verificationToken();

        $user_set = M("user_set");
        $ret = $user_set->where(array('user_id' => I('uid')))->find();

        //判断当前用户是否有设置如果没有则初始化
        if ($ret) {//db_user_set数据存在
            return RET(0, "获取用户设置成功！", $ret);

        } else {//db_user_set数据不存在
            $data = array('user_id' => I('uid')
            , 'is_incubator' => 1
            , 'is_call' => 1);

            $add_ret = $user_set->add($data);

            $search_ret = $user_set->where(array('user_set_id' => $add_ret))->find();//反查，因为数据库里还有其他的字段，虽然是null

            if ($add_ret && $search_ret) {//添加成功

                return RET(0, "获取用户设置成功！", $search_ret);
            } else {
                return RET_NO_V(1, "获取用户设置失败！");
            }
        }
    }

    /**
     * @api {get} setUserSetCollection/token/:token/uid/:uid 用户设置代收货款
     * @apiName 用户设置代收货款（判断协议）
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} collection_account 账号.
     * @apiParam {String} collection_name 姓名.
     **/
    function setUserSetCollection()
    {
        //校验token
        verificationToken();
        $user_set = M("user_set");
        $ret = $user_set->where(array('user_id' => I('uid')))->save(array('collection_account' => I('collection_account'), 'collection_name' => I('collection_name')));
        if ($ret) {
            return RET_NO_V(0, "更新代收货款数据成功！");
        } else {
            return RET_NO_V(1, "更新代收货款数据失败！");
        }
    }

    /**
     * @api {get} setUserSetOther/token/:token/uid/:uid/type/:type/is_incubator/:is_incubator/is_call/:is_call 用户设置
     * @apiName 用户设置
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} type 1取货配备保温箱判断 2 取货不要给我打电话.
     * @apiParam {Int} is_incubator 取货时配备保温箱
     * @apiParam {Int} is_call 取货时不要打电话
     **/
    function setUserSetOther()
    {
        //校验token
        verificationToken();

        $type = I('type');
        $user_set = M("user_set");


        if ($type == 1) {
            $ret = $user_set->where(array('user_id' => I('uid')))->save(array('is_incubator' => I('is_incubator')));
            if ($ret) {
                return RET_NO_V(0, "更新取货配备保温箱判断成功！");
            } else {
                return RET_NO_V(1, "更新取货配备保温箱判断失败！");
            }
        } elseif ($type == 2) {
            $ret = $user_set->where(array('user_id' => I('uid')))->save(array('is_call' => I('is_call')));
            if ($ret) {
                return RET_NO_V(0, "更新取货不要给我打电话成功！");
            } else {
                return RET_NO_V(1, "更新取货不要给我打电话失败！");
            }
        }

    }

    /**
     * @api {get} userRegistrationID/token/:token/uid/:uid/userRegistrationID/:userRegistrationID 用户推送ID
     * @apiName 每次登录获取一次更新一次此RegistrationID
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} registrationID 推送ID
     **/
    function userRegistrationID()
    {
        //校验token
        verificationToken();
        $app_users = M("app_users");
        $ret = $app_users->where(array('user_id' => I('uid')))->save(array('jpush_id' => I("registrationID")));
        if ($ret) {
            return RET_NO_V(0, "推送绑定成功！");
        } else {
            return RET_NO_V(1, "推送绑定失败！");
        }
    }

    /**
     * @api {get} pkRegistrationID/token/:token/uid/:uid/userRegistrationID/:userRegistrationID 用户推送ID
     * @apiName 每次登录获取一次更新一次此RegistrationID
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} registrationID 推送ID
     **/
    function pkRegistrationID()
    {
        //校验token
        pnerificationToken();
        $dispatch = M("dispatch");
        $ret = $dispatch->where(array('dispatch_id' => I('uid')))->save(array('jpush_id' => I("registrationID")));
        if ($ret) {
            return RET_NO_V(0, "推送绑定成功！");
        } else {
            return RET_NO_V(1, "推送绑定失败！");
        }
    }


    /**
     * @api {get} getOpenCity/token/:token/uid/:uid 获取开通城市数据
     * @apiName 获取开通城市数据
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     **/

    function getOpenCity()
    {
        //校验token
        verificationToken();
        $pricing_tactics = M('pricing_tactics');
        $ret = $pricing_tactics->field('province_id,city_id')->select();
        $new_ret = array();
        foreach ($ret as $k => $v) {
            $new_ret[] = city_name($ret[$k]['city_id']);
        }
        if ($ret) {
            return RET(0, "获取开通城市成功！", $new_ret);
        } else {
            return RET_NO_V(1, "获取开通城市失败！");
        }
    }

    /**
     * @api {get} getAddress/token/:token/uid/:uid 获取用户地址
     * @apiName 获取用户地址
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     **/

    function getAddress()
    {
        verificationToken();
        $common_address = M('common_address');
        $ret = $common_address->where(array('user_id' => I('uid')))->order('address_id desc')->select();
        if ($ret) {
            return RET(0, "获取用户地址成功！", $ret);
        } else {
            return RET_NO_V(1, "获取用户地址失败！");
        }
    }


    /**
     * @api {get} getUserMassageContent/token/:token/uid/:uid/message_id/:message_id 用户消息消息中心
     * @apiName 用户消息消息中心
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {Int} message_id 消息ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     **/

    function getUserMassageContent()
    {
        verificationToken();
        $message = M('message');
        $ret = $message->where(array('message_id' => I('message_id'), 'message_type' => 1))->find();
        $ret['content'] = htmlspecialchars_decode($ret['content']);
        if ($ret) {
            return RET(0, "获取消息成功！", $ret);
        } else {
            return RET_NO_V(1, "获取消息失败！");
        }
    }

    /**
     * @api {get} getMassage/token/:token/uid/:uid 用户消息中心
     * @apiName 用户消息中心
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     **/
    function getMassage()
    {
        verificationToken();
        $message = M('message');
        $count = $message->where(array('message_type' => 1))->count();
        $ret = $message->where(array('message_type' => 1))->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->order('message_id desc')->select();
        $rets['data'] = $ret;
        $rets['count'] = ceil($count / I("pagenum"));
        if ($ret) {
            return RET(0, "获取消息成功！", $rets);
        } else {
            return RET_NO_V(1, "获取消息失败！");
        }
    }

    /**
     * @api {get} getUserRecommendCash/token/:token/uid/:uid/ 获取推荐跑客奖励的金额
     * @apiName 获取推荐跑客奖励的金额
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     **/

    function getUserRecommendCash()
    {
        $ret = array('active_amount' => C('active_amount'));
        if ($ret) {
            return RET(0, "获取成功！", $ret);
        } else {
            return RET_NO_V(1, "获取失败！");
        }
    }


    /**
     * @api {get} getOrderStatus/order_id/:order_id.uid/:uid/token/:token 获取订单状态
     * @apiName 获取订单状态
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} order_id 订单ID.
     **/
    function getOrderStatus()
    {
        verificationToken();

        $order = M('order');
        $rets = $order->where(array('order_id' => I('order_id')))->field('status')->find();
        if ($rets) {
            return RET(0, "获取订单状态成功！", $rets);
        } else {
            return RET_NO_V(1, "获取订单状态失败！");
        }
    }

    /**
     * @api {get} getOrderMoney/uid/:uid/token/:token/ 获取订单价格
     * @apiName 获取订单价格(起步价2公里（含2公里），每单8元；3公里12元；3-10公里之间每公里加1元；10-30公里以后，每公里加2元；超出30公里后每公里加3元)
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} cityId 城市ID.
     * @apiParam {String} appointmentTime 预约时间 选填.
     * @apiParam {String} startLat 开始的维度.
     * @apiParam {String} startLng 开始的经度.
     * @apiParam {String} endLat 结束的维度.
     * @apiParam {String} endLng 结束的经度.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *"retCode": 0,
     *"retDesc": "计算成功！",
     *"retValue": {
     *"duration": 13,           //所需时间
     *"totalPrice": 20.4, //总价= 起步价 + 里程费 + 夜间加价 + 临时加价
     *"totalkilometre": 3, //总公里数
     *"startkilometres": 2, //起步公里
     *"startmoney": 8,      // 起步价
     *"kilometres": 1,      // 里程数
     *"money": 4,           // 里程费
     *"nightAdd": 5,         //夜间加价
     *"addPrice": 3.4        //临时加价
     * "userCouponId": 3.4        //使用优惠券id
     * "couponTitle": 3.4        //优惠券标题
     *" couponMoney" //优惠之后的金额
     *}
     *}
     **/

    function getOrderMoney()
    {
        //接口权限校验
        verificationToken();
        $start = I('startLat') . "," . I('startLng');
        $end = I('endLat') . "," . I('endLng');
//        $start = '34.8029730000,113.6080970000';
//         $end = '34.8161290000,113.6193080000';
        $ret = line_uu($start, $end);

        //获取公里数取整
        $distance = $ret['message'];

        //获取公里数取整
        $kilometre = number_format($distance / 1000, 2);

        //$duration = $ret['result']['routes'][0]['duration'];

        //$duration = number_format($duration / 60, 2);
        //$data['duration'] = $duration;
        $cityId = (float)I('cityId');

        $twoStartKiloMoney = getTwoStartKiloMoney($cityId, $kilometre);//返回起步价、里程费、总价等数组
//        dump($twoStartKiloMoney);
        $totalPrice = $twoStartKiloMoney['totalPrice'];//总里程金额
        $data['totalPrice'] = format_money($totalPrice);

        $data['totalkilometre'] = $kilometre;

        $pricing_tactics = M('pricing_tactics');
        //夜间加价
        $nightAdd = 0;
        $ret = $pricing_tactics->where(array('city_id' => $cityId))->field('tactics_array')->find();
//    ["startkilometres"] => string(1) "3"
//    ["startmoney"] => string(1) "9"
//    ["totalPrice"] => float(14)
//    ["money"] => float(5)
//    ["kilometres"] => float(3)
        if ($ret['tactics_array']) {
            $tactics_array = json_decode($ret['tactics_array'], TRUE);
            $mileage = $tactics_array['mileage'];
            $night = $tactics_array['night'];
            $data['startkilometres'] = format_money($twoStartKiloMoney['startkilometres']);
            $data['startmoney'] = format_money($twoStartKiloMoney['startmoney']);

            $data['kilometres'] = 0.00;
            if ($kilometre - format_money($twoStartKiloMoney['startkilometres']) > 0.00)
                $data['kilometres'] = $kilometre - format_money($twoStartKiloMoney['startkilometres']);

            $data['money'] = format_money($twoStartKiloMoney['money']);
            $data['nightAdd'] = format_money($nightAdd);
            $date = null;

            /*$time = "2016-1-10 23:23";
            $date = substr($time,-5,5);
            dump($date);*/
            if (I('appointmentTime')) {
                $date = substr(I('appointmentTime'), -5, 5);
            } else {
                $date = date('H:i');
            }
            for ($i = 0; $i < count($night); $i++) {
                $startTime = $night[$i]['startTime'];
                $endTime = $night[$i]['endTime'];
                if ($startTime <= $date) {
                    if ($endTime > $date) {
                        $nightAdd += $night[$i]['addMoney'];
                        $data['nightAdd'] = format_money($nightAdd);
                        $totalPrice += $nightAdd;
                        break;
                    }
                }
            }
            $temporary = $tactics_array['temporary'];
//            dump($temporary);
            $addPrice = number_format($totalPrice * ($temporary["addtimes"] - 1), 2);

            $data['addPrice'] = $addPrice;
            $totalPrice += $addPrice;
            $data['totalPrice'] = number_format($totalPrice, 2);
            $return = couponUse(I('uid'), $totalPrice);
            $data['userCouponId'] = $return['userCouponId'];
            $data['couponTitle'] = $return['couponTitle'];
            $data['couponMoney'] = $return['couponMoney'];
            $data['coupon_value'] = $return['coupon_value'];
//            dump('data:');
//            dump($data);
//            dump($data);
            return RET(0, "计算成功！", $data);
        } else {
            return RET_NO_V(1, "计算失败！");
        }

        //dump();
        //exit();
        //获取两点之间的距离
        // $Distance = getDistanceBetweenPointsNew(I('startLat'), I('startLng'), I('endLat'), I('endLng'));
        //换算公里数
        //$kilometre = intval(round($Distance["kilometers"]));
        /*$data = array();
        $data['distance'] = $kilometre . '公里';
        $data['duration'] = '预计' . round($duration / 60) . '分钟可以到达';
        *///小于2公里
        /*if ($kilometre <= 2) {
            $data['cost'] = C("START_COST") . "元";
            $data['content'] = "小于2公里，无加价";
            //3公里
        } elseif ($kilometre > 2 && $kilometre <= 3) {
            $data['cost'] = (C("START_COST") + 4) . "元";
            $data['content'] = "3公里收费12元";
        } elseif ($kilometre > 3 && $kilometre <= 10) {
            $data['cost'] = (C("START_COST") + 4) + ($kilometre - 3) . "元";
            $data['content'] = "超过3公里，超出" . ($kilometre - 3) . '公里,加收' . (($kilometre - 3) * C('3_10price'));
        } elseif ($kilometre > 10 && $kilometre <= 30) {
            $data['cost'] = (C("START_COST") + 4) + ($kilometre - 3) + (($kilometre - 10) * C('10_30price')) . "元";
            $data['content'] = "超过10公里，超出" . ($kilometre - 10) . '公里,加收' . (($kilometre - 10) * 2) . '元';
        } elseif ($kilometre > 30) {
            $data['cost'] = (C("START_COST") + 4) + ($kilometre - 3) + (($kilometre - 10) * C('10_30price')) + (($kilometre - 30) * C('30price')) . "元";
            $data['content'] = "超过30公里，超出" . ($kilometre - 30) . '公里,加收' . (($kilometre - 20) * 3) . '元';
        }*/


    }

    /**
     * @api {get} getLineUpMoney/uid/:uid/token/:token/ 获取排队订单价格
     * @apiName 获取订单价格(起步价10元（含30分钟），每30分钟加10元)
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} cityId 城市ID.
     * @apiParam {String} timeslong 排队时长.
     * @apiParam {String} appointmentTime 预约时间 选填.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *"retCode": 0,
     *"retDesc": "计算成功！",
     *"retValue": {
     *"lineUpMoney": 20.4, //总价
     *"startlineTime": 30, //起步分钟
     *"startMoney": 10,      // 起步价
     *"money": 4,           // 费用
     *"nightAdd": 5,         //夜间加价
     *"addPrice": 3.4        //临时加价
     * "couponMoney": 3.4        //优惠之后价格
     * "couponTitle": 3.4        //优惠标题
     * "CouponId": 3.4        //优惠券id
     *}
     *}
     **/

    function getLineUpMoney()
    {
        verificationToken();
        $pricing_tactics = M('pricing_tactics');
        $ret = $pricing_tactics->where(array('city_id' => I('cityId')))->field('tactics_array')->find();
        if ($ret['tactics_array']) {
            $tactics_array = json_decode($ret['tactics_array'], TRUE);
            $is_starting_price = $tactics_array['is_starting_price'];
            $data['startMoney'] = format_money($is_starting_price[0]['lineKoney']);
            $data['startlineTime'] = $is_starting_price[0]['lineTime'];
            $line_up = $tactics_array['line_up'];
            $night = $tactics_array['night'];
            $pricePer = $line_up[0]['pricePer'];
            $lineUpMoney = ceil(I('timeslong') / 30) * $pricePer;
            $data['money'] = format_money($lineUpMoney - $data['startMoney']);
            $data['lineUpMoney'] = format_money($lineUpMoney);
            $nightAdd = 0;
            $data['nightAdd'] = format_money($nightAdd);
            $date = null;
            /*$time = "2016-1-10 23:23";
            $date = substr($time,-5,5);
            dump($date);*/
            if (I('appointmentTime')) {
                $date = substr(I('appointmentTime'), -5, 5);
            } else {
                $date = date('H:i');
            }
            for ($i = 0; $i < count($night); $i++) {
                $startTime = $night[$i]['startTime'];
                $endTime = $night[$i]['endTime'];
                if ($startTime <= $date) {
                    if ($endTime > $date) {
                        $nightAdd += $night[$i]['addMoney'];
                        $data['nightAdd'] = format_money($nightAdd);
                        $lineUpMoney += $nightAdd;
                        break;
                    }
                }
            }
            $temporary = $tactics_array['temporary'];
            $addPrice = format_money($lineUpMoney * ($temporary["addtimes"] - 1));

            $data['addPriceDesc'] = $temporary['addtimes_reson'];
            $data['addPrice'] = $addPrice;
            $lineUpMoney += $addPrice;
            $return = couponUse(I('uid'), $lineUpMoney);
            $data['lineUpMoney'] = format_money($lineUpMoney);
            $data['couponMoney'] = number_format($return['couponMoney'], 2);
            $data['couponTitle'] = $return['couponTitle'];
            $data['CouponId'] = $return['userCouponId'];
            $data['coupon_value'] = $return['coupon_value'];
            return RET(200, "返回成功", $data);
        } else {
            return RET_NO_V(400, "计算失败！");
        }
    }

    /**
     * @api {get} getSMS/phone/:phone 获取短信验证码
     * @apiName 获取短信验证码
     * @apiGroup pt
     *
     * @apiParam {Int} phone 获取短信验证码的手机号.
     **/
    function getSMS()
    {
        if ($this->sendMSM(I('phone'))) {
            return RET_NO_V(0, "短信发送成功！");
        } else {
            return RET_NO_V(1, "短信发送失败！");
        }

    }

    /**
     * @api {get} getUserCoupon/uid/:uid/token/:token 获取优惠券
     * @apiName 获取优惠券
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *   "retCode": 0,                    //0 代表成功 1代表失败
     *   "retDesc": "获取优惠券成功！",       //优惠券状态
     *   "retValue": [
     *   {
     *   "user_coupon_id": "1",       //优惠券ID
     *   "coupon_id":"1",
     *   "user_id": "35",        //用户ID
     *   "coupon_type": "1",     //1抵扣券2折扣券
     *   "coupon_value": "10",   //数值
     *   "remark": "炎炎夏日优惠补贴",   //优惠券备注
     *   "valid_end_time": "2016-07-31 00:00:00",    //优惠券过期时间
     *   "from_remark": null,    //来源备注
     *   "is_used": "0",         //是否已经使用
     *   "highest_deduct_amount": "10.00"    //最高折扣
     *   }
     *   ]
     *    }
     *
     * @apiError retCode=1为返回数据错误.
     *
     */
    function getUserCoupon()
    {
        //接口权限校验
        verificationToken();
        $user_coupon = M('user_coupon');
        $count = $user_coupon->where(array('user_id' => I('uid'), 'is_used' => 1,'valid_end_time'=>array('EGT',date('Y-m-d H:i:s', time()))))->count();
        $ret = $user_coupon->where(array('user_id' => I('uid'), 'is_used' => 1,'valid_end_time'=>array('EGT',date('Y-m-d H:i:s', time()))))->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->select();

        $rets['data'] = $ret;
        $rets['count'] = ceil($count / I("pagenum"));

        //将未使用的、已过期的优惠券，状态置为3
        $valid_obj = $user_coupon->field('GROUP_CONCAT(user_coupon_id) as user_coupon_id')->where(array('user_id' => I('uid'), 'is_used' => 1,'valid_end_time'=>array('lt',date('Y-m-d H:i:s', time()))))->find();

        if(!empty($valid_obj['user_coupon_id'])){
            $user_coupon->where("user_coupon_id in (".$valid_obj['user_coupon_id'].")")->save(array('is_used'=>3));
        }
        if ($ret) {
            return RET(0, "获取数据成功！", $rets);
        } else {
            return RET_NO_V(1, "获取数据失败！");
        }
    }

    /**
     * @api {get} getUserCenter/uid/:uid/token/:token 获取系统用户中心统计数据
     * @apiName 获取系统用户中心统计数据
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *          "retCode": 0,
     *          "retDesc": "获取成功!",
     *          "retValue": {
     *          "user_coupon_count": "0",               //用户优惠券数量
     *          "user_purse_balance": {
     *                  "purse_balance": "0.00",        //用户余额
     *                  "avatar": "../image/left_bg.png"//用户头像
     *                      }
     *                 }
     *     }
     *
     * @apiError retCode=1为返回数据错误.
     *
     */

    public function getUserCenter()
    {
        //接口权限校验
        verificationToken();
        $ret = array();
        $user_coupon = M('user_coupon');
        $app_users = M('app_users');
        //is_used  1未使用 2已使用
        $ret['user_coupon_count'] = $user_coupon->where(array('user_id' => I('uid'), 'is_used' => 1))->count();
        $ret['user_purse_balance'] = $app_users->where(array('user_id' => I('uid')))->field('purse_balance,avatar,growth_value,points_value')->find();
        return RET(0, "获取成功!", $ret);
    }


    /**
     * @api {get} getUserOrder/uid/:uid/token/:token/status/:status/page/:page/pagenum/:pagenum 获取用户订单
     * @apiName 获取用户订单
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} status 订单状态. 0、未分配，1、已分配，2、已取件，3、已送达，4、已完成，9，已取消。
     * @apiParam {String} pay_status 0，未支付，1、已支付，2、已退款'
     * @apiParam {String} pagenum 每一页的条数.
     * @apiParam {String} page 获取的页数.
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *          "retCode": 0,
     *          "retDesc": "获取成功!",
     *          "retValue": {
     *         }
     *     }
     *
     * @apiError retCode=1为返回数据错误.
     *
     */
    public function getUserOrder()
    {
        //接口权限校验
        verificationToken();
        $order = M('order');
        if (I('status')) {
            $map['status'] = I('status');
            $map['user_id'] = I('uid');
            if (2 == I('status')) {
                $map['status'] = array('between', '2,6');
            }
            $count = $order->where($map)->count();
            $ret = $order->where($map)->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->field('status,pay_status,reci_address_floor,pay_method,reci_address,send_address,order_time,real_amount,order_id,order_type,send_address_floor,queue_address,reservation_time,is_reservation')->order('order_id desc')->select();
        } else {
            $count = $order->where(array('user_id' => I('uid'), 'status' => I('status'), 'pay_status' => I("pay_status")))->count();
            $ret = $order->where(array('user_id' => I('uid'), 'status' => I('status'), 'pay_status' => I("pay_status")))->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->field('status,pay_status,pay_method,reci_address_floor,reci_address,send_address_floor,send_address,order_time,real_amount,order_id,order_type,queue_address,reservation_time,is_reservation')->order('order_id desc')->select();
        }
        $rets['data'] = $ret;
        $rets['count'] = ceil($count / I("pagenum"));
        if ($ret) {
            return RET(0, "获取订单数据成功!", $rets);
        } else {
            return RET_NO_V(1, "暂无数据!");
        }
    }


    /**
     * @api {get} getUserAllOrder/uid/:uid/token/:token/page/:page/pagenum/:pagenum 获取用户订单
     * @apiName 获取用户所有订单
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} pagenum 每一页的条数.
     * @apiParam {String} page 获取的页数.
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *          "retCode": 0,
     *          "retDesc": "获取成功!",
     *          "retValue": {
     *         }
     *     }
     *
     * @apiError retCode=1为返回数据错误.
     *
     */
    public function getUserAllOrder()
    {
        //接口权限校验
        verificationToken();
        $order = M('order');
        $count = $order->where(array('user_id' => I('uid')))->count();
        $ret = $order->where(array('user_id' => I('uid')))->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->field('status,reci_address_floor,pay_status,pay_method,reci_address,send_address,order_time,real_amount,send_address_floor,order_id,order_type,queue_address,reservation_time,is_reservation')->order('order_id desc')->select();
        $rets['data'] = $ret;
        $rets['count'] = ceil($count / I("pagenum"));
        if ($ret) {
            return RET(0, "获取所有订单数据成功!", $rets);
        } else {
            return RET_NO_V(1, "暂无数据!");
        }
    }


    /**
     * @api {get} get_city_id/uid/:uid/token/:token/city/:city 由城市名称获取城市ID
     *
     * @apiName 由城市名称获取城市ID
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} city 城市中文名
     */
    public function getCityId()
    {
        $location = M('location');
        $ret = $location->where(array('city' => I('city_name')))->field('id')->cache(true)->find();
        if ($ret) {
            return RET(1, "获取城市ID成哥", $ret['id']);
        } else {
            return RET_NO_V(0, "获取城市ID失败");
        }
    }

    /**
     * @api {get} userCouponExchange/uid/:uid/token/:token/key/:key
     * @apiName 优惠券兑换
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} key 兑换key.
     *
     */
    function userCouponExchange()
    {
        verificationToken();
        //查询优惠信息
        $coupon_info = M("coupon_info");
        $ret = $coupon_info->where(array('coupon_key' => I('key')))->field('title,is_push,coupon_id,coupon_type,coupon_value,valid_end_time,surplus_num')->find();
        //判断是否有优惠券
        if ($ret) {
            if ($ret['is_push'] == 0) {
                RET_NO_V(1, "抱歉,此优惠券暂没有发布！");
            } else {
//                dump($ret);
                //判断是否数量够不够
                if ((int)$ret['surplus_num'] > 0) {
                    //判断是否过期
                    //if ($ret['valid_end_time'] >= date('Y-m-d H:i:s', time())) {
                    //给用户加优惠券
                    $user_coupon = M("user_coupon");
                    $rets = $user_coupon->where(array('user_id' => I('uid'), 'coupon_key' => I('key')))->find();
                    if ($rets) {
                        RET_NO_V(2, "抱歉,您已兑换过此优惠！");
                        return;
                    } else {
                        //判断优惠券类型
                        switch ($ret['coupon_type']) {
                            //抵扣券
                            case 1:
                                $data = array(
                                    'coupon_type' => 1,     //优惠券类型
                                    'coupon_id' => $ret['coupon_id'],
                                    'user_id' => I('uid'),    //用户id
                                    'coupon_value' => $ret['coupon_value'],   //数值
                                    'remark' => $ret['title'],   //说明
                                    'valid_end_time' => coupon_valid_end(I('key')),    //有效截至时间
                                    'from_remark' => "APP兑换抵扣券，金额为" . $ret['coupon_value'] . '元',
                                    'is_used' => 1,       //是否被用 1未使用2已使用
                                    'coupon_key' => I('key')
                                    //'highest_deduct_amount'=>10   //最高抵扣金额
                                );
                                $ret_status = $user_coupon->add($data);
                                if ($ret_status) {
                                    $ret_coupon = $coupon_info->where(array('coupon_id' => $ret['coupon_id']))->save(array('surplus_num' => ($ret['surplus_num'] - 1)));
                                    if ($ret_coupon) {
                                        RET_NO_V(0, "恭喜，您已成功兑换！");
                                    } else {
                                        RET_NO_V(1, "抱歉兑换此优惠码失败！");
                                    }
                                } else {
                                    RET_NO_V(1, "抱歉兑换此优惠码失败！");
                                }
                                break;
                            //折扣券
                            case 2:
                                $data = array(
                                    'coupon_type' => 2,     //优惠券类型
                                    'user_id' => I('uid'),    //用户id
                                    'coupon_value' => $ret['coupon_value'],   //数值
                                    'coupon_id' => $ret['coupon_id'],
                                    'remark' => $ret['title'],   //说明
                                    'valid_end_time' => $ret['valid_end_time'],    //有效截至时间
                                    'from_remark' => "APP兑换折扣券，折扣为" . $ret['coupon_value'] . '%',
                                    'is_used' => 1,       //是否被用 1未使用2已使用
                                    'coupon_key' => I('key')
                                    //'highest_deduct_amount'=>10   //最高抵扣金额
                                );
                                $ret_status = $user_coupon->add($data);
                                if ($ret_status) {
                                    $ret_coupon = $coupon_info->where(array('coupon_id' => $ret['coupon_id']))->save(array('surplus_num' => ($ret['surplus_num'] - 1)));
                                    if ($ret_coupon) {
                                        RET_NO_V(0, "恭喜，您已成功兑换！");
                                    } else {
                                        RET_NO_V(1, "抱歉兑换此优惠码失败！");
                                    }
                                } else {
                                    RET_NO_V(1, "抱歉兑换此优惠码失败！");
                                }
                                break;
                        }
                    }
                    //} else {
                    //    RET_NO_V(4, "抱歉此优惠码已过兑换时间！");
                    //   return;
                    //}

                } else {
                    RET_NO_V(3, "抱歉此优惠券已经被兑换完毕");
                    return;
                }

            }
        } else {
            RET_NO_V(1, "抱歉无此优惠券码");
            return;
        }
    }


    /**
     * @api {get} addUserAddress/token/:token/uid/:uid/moreaddress/:moreaddress/address_name/:address_name/detail_address/:detail_address/latitude/:latitude/longitude/:longitude/poi_uid/:poi_uid 新增用户收藏地址
     * @apiName 新增用户收藏地址
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} address_name 名称.
     * @apiParam {String} detail_address 详细地址.
     * @apiParam {String} moreaddress 更多地址.
     * @apiParam {String} latitude 纬度
     * @apiParam {String} longitude 经度.
     **/
    function addUserAddress()
    {
        verificationToken();
        $common_address = M('common_address');
        $ret = $common_address->where(array('user_id' => I('uid')))->add(array('user_id' => I('uid'), 'moreaddress' => I('moreaddress'), 'address_type' => 1, 'address_name' => I('address_name'), 'detail_address' => I('detail_address'), 'latitude' => I('latitude'), 'longitude' => I('longitude'), 'tel' => I('tel'), 'poi_uid' => I('poi_uid')));

        if ($ret) {
            return RET_NO_V(0, "新增用户地址成功！");
        } else {
            return RET_NO_V(1, "新增用户地址失败！");
        }
    }

    /**
     * @api {get} editUserAddress/token/:token/uid/:uid/address_id/:address_id/moreaddress/:moreaddress/address_name/:address_name/detail_address/:detail_address/latitude/:latitude/longitude/:longitude 用户地址编辑
     * @apiName 用户地址编辑
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} address_id 地址id.
     * @apiParam {String} address_name 名称.
     * @apiParam {String} detail_address 详细地址.
     * @apiParam {String} moreaddress 更多地址.
     * @apiParam {String} latitude 纬度
     * @apiParam {String} longitude 经度.
     **/

    function editUserAddress()
    {
        verificationToken();
        $common_address = M('common_address');
        $ret = $common_address->where(array('address_id' => I('address_id'), 'user_id' => I('uid')))->save(array('address_type' => 1, 'moreaddress' => I('moreaddress'), 'address_name' => I('address_name'), 'detail_address' => I('detail_address'), 'latitude' => I('latitude'), 'longitude' => I('longitude')));
        if ($ret) {
            return RET_NO_V(0, "编辑用户地址成功！");
        } else {
            return RET_NO_V(1, "编辑用户地址失败！");
        }
    }

    /**
     * @api {get} delUserAddress/token/:token/uid/:uid/address_id/:address_id 删除用户地址收藏
     * @apiName 删除用户地址收藏
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} address_id 地址id.
     **/
    function delUserAddress()
    {
        verificationToken();

        $common_address = M('common_address');
        $ret = $common_address->where(array('address_id' => I('address_id'), 'user_id' => I('uid')))->delete();
        if ($ret) {
            return RET_NO_V(0, "删除用户地址成功！");
        } else {
            return RET_NO_V(1, "删除用户地址失败！");
        }
    }


    /**
     * @api {get} order/token/:token/uid/:uid/real_amount/：real_amount/order_amount/：order_amount/pay_method/：pay_method/order_number/:order_number/order_type/:order_type/city_id/:city_id/user_id/:user_id/ 发起订单接口
     * @apiName 发起订单接口
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} order_type 订单类型.1取送订单，2，代买订单，3，代排队订单
     * @apiParam {String} city_id 城市id（1）先默认为1.
     * @apiParam {String} res_type 物品类型. 美食|生鲜|鲜花    |排队类型
     * @apiParam {String} reci_mobile 收件人电话.
     * @apiParam {String} voucher_no 商户订单id
     * @apiParam {String} reci_address 收件人地址.
     * @apiParam {String} reci_latit 收件人位置纬度 | 排队位置维度.
     * @apiParam {String} reci_longit 收件人位置经度 | 排队位置经度.
     * @apiParam {String} send_mobile 发件人电话.
     * @apiParam {int} order_amount 订单金额
     * @apiParam {int} real_amount 实付金额
     * @apiParam {int} pay_method 1.支付宝 2.微信 3.钱包
     * @apiParam {String} send_address 发件人地址.
     * @apiParam {String} send_latit 发件人位置纬度 | 排队下单人位置维度.
     * @apiParam {String} send_longit 发件人位置经度 | 排队下单人位置经度.
     * @apiParam {String} is_reservation 是否预约单.
     * @apiParam {String} reservation_time 预约时间.
     * @apiParam {String} remark_voice 补充说明语音地址.
     * @apiParam {String} remark 补充说明.
     * @apiParam {int} conveyance_id 运输工具ID.
     * @apiParam {String} up_server 升级服务.
     * @apiParam {decimal} fee 小费.
     * @apiParam {decimal} company_id 跑客团队ID.get
     *
     * //代买订单增加的参数
     * @apiParam {int} is_have_price [帮我买]是否知道价格0默认值 1 知道价格 2不知道价格.
     * @apiParam {decimal} goods_amount 帮我买商品金额:商品金额为0时，表示用户不知道价格。如果不为0，支付时需要计算该金额
     *
     * //排队订单增加的参数
     * @apiParam {String} replace_mobile 代他人排队电话.
     * @apiParam {String} queue_address 排队地点.
     * @apiParam {datetime} queue_time 排队时间.
     * @apiParam {String} hour_long 排队时长.
     * @apiParam {String} delayed 延长时长.
     **/

    function order()
    {
        verificationToken();
        $_GET['user_id'] = I('uid');
        $_GET['res_type'] = trim(I('res_type'));
        $order_amounts = 0.00;
        $order_amount_cal = 0.00;
        $nightAdd = 0.00;
        $addPrice = 0.00;
        $send_latit = I('send_latit');
        $send_longit = I('send_longit');
        $reci_latit = I('reci_latit');
        $reci_longit = I('reci_longit');
//        dump(I('order_type'));
        if (I('order_type') == 3) {
            if (!I('queue_time'))
                $_GET['queue_time'] = date('Y-m-d H:i:s', time());

            $order_amounts = get_line_up_money(I('uid'), I('city_id'), I('hour_long'), I('order_time'));
//           dump($order_amounts);
//           die;
            $startMoney = $order_amounts['startMoney'];//起步价
            $money = $order_amounts['money'];//排队费
            $nightAdd = $order_amounts['nightAdd'];//夜间加价
            $addPrice = $order_amounts['addPrice'];//临时加价
            $coupon_value = $order_amounts['coupon_value'];//抵扣券的金额或折扣券的优惠金额【总之，是优惠金额】
//            dump("初始起步价：".$startMoney);
//            dump("排队费：".$money);

            //============选择团队：默认不加费用，大河+1元，直属+2元 start===============
            $totalPrice = $startMoney + $money;
//            dump( '起步价+排队费：');
//            dump($totalPrice);

            if (I('company_id') == 3) {
                $order_amount_cal = $totalPrice + 2;//直属团队
            } elseif (I('company_id') == 2) {
                $order_amount_cal = $totalPrice + 1;//大河团队
            } elseif (I('company_id') == 5) {
                $order_amount_cal = $totalPrice - 7;//校园团队
            } else
                $order_amount_cal = $totalPrice;
//            dump( '排队适配团队后的金额：');
//            dump($order_amount_cal);

            //============选择团队：默认全部不加费用，大河+1元，直属+2元 end===============
        } else {
            if (2 == I('order_type')) {
                $send_latit = I('reci_latit');
                $send_longit = I('reci_longit');
                $reci_latit = I('send_latit');
                $reci_longit = I('send_longit');
            }
            $order_amounts = get_order_money($send_latit, $send_longit, $reci_latit, $reci_longit, I('city_id'));//计算跑腿费=距离跑腿费+夜间加价+临时加价-优惠券
//            dump('获取跑腿费对象');
//            dump($order_amounts);
            $totalkilometre = $order_amounts['totalkilometre'];//订单的总公里数
            $totalPrice = $order_amounts['totalPrice'];//里程费+夜间加价+临时加价
            $coupon_value = $order_amounts['coupon_value'];//抵扣券的金额或折扣券的优惠金额【总之，是优惠金额】
            $startMoney = $order_amounts['startmoney'];//起步价
            $money = $order_amounts['money'];//排队费
            $nightAdd = $order_amounts['nightAdd'];//夜间加价
            $addPrice = $order_amounts['addPrice'];//临时加价

//            dump("初始起步价：".$startMoney);
//            dump("里程费：".$money);
            $total_amount = $startMoney + $money;
//            dump( '起步价+里程费：');
//            dump($total_amount);

            //=============车型：1电动车，2三轮车，3面包车 start===========

            if (I('conveyance_id') == 2)
                $order_amount_cal = $total_amount * 1.5;//三轮车跑腿费
            elseif (I('conveyance_id') == 3)
                $order_amount_cal = $total_amount * 2.5;//面包车跑腿费
            else
                $order_amount_cal = $total_amount;

//            dump( '适配车型后的金额：');
//            dump($order_amount_cal);

            //=============车型：1电动车，2三轮车，3面包车 end===============

            //============选择团队：默认不加费用，大河+1元，直属+2元 start===============
            if (I('company_id') == 2)
                $order_amount_cal = $order_amount_cal + 1;//大河团队
            elseif (I('company_id') == 3)
                $order_amount_cal = $order_amount_cal + 2;//直属团队
            elseif (I('company_id') == 5) {
                if ($totalkilometre < 2.5) {
                    $order_amount_cal = $order_amount_cal - 3;
                } else {
                    $order_amount_cal = $order_amount_cal - 7;//校园团队
                }
                //$order_amount_cal = $order_amount_cal - 7 ;//校园团队
            }
//            dump( '适配团队后的金额：');
//            dump($order_amount_cal);
            //============选择团队：默认全部不加费用，大河+1元，直属+2元 end===============
        }
//        dump('金额：'.$order_amount_cal);
//        dump('临时：'.$addPrice);
//        dump('夜间：'.$nightAdd);
//        dump('优惠金额：'.$coupon_value);

        $order_amount_cal = $order_amount_cal + $nightAdd + $addPrice - $coupon_value;
//        dump('金额+临时+夜间—优惠券后的金额：'.$order_amount_cal);
        if ($order_amount_cal <= 0)
            $order_amount_cal = 0;
//        dump('正值不变，负值归零：'.$order_amount_cal);

        $up_server = trim(I('up_server'));//1|2|3|4|5  服务升级： 加急|保险|是否保温配送|是否易碎|是否贵重
//        dump('服务升级：'.$up_server);
        if ($up_server) {
            $up_server_arr = explode("|", $up_server);
            foreach ($up_server_arr as $value) {
                if ($value == 1) {
                    $_GET['is_insured'] = 1;
                    $_GET['insured_amount'] = 5;//加急费用
                    $order_amount_cal += 5;//计算跑腿费　＋=　加急费用
                }
                if ($value == 2) {
                    $_GET['is_insurance'] = 1;
                    $_GET['insurance_amount'] = 5;//保险费用
                    $order_amount_cal += 5;//计算跑腿费 +=　保险费用
                }

                if ($value == 3)
                    $_GET['is_incubator'] = 1;
                if ($value == 4)
                    $_GET['is_fragile'] = 1;
                if ($value == 5)
                    $_GET['is_valuables'] = 1;
                if ($value == 6) {
                    $_GET['is_sms'] = 1;
                    $_GET['is_sms_amount'] = 1;
//                    dump('888888888888888888====='.$order_amount_cal);
                    $order_amount_cal = $order_amount_cal + 1;
//                    dump('==========================='.$order_amount_cal);
                }

            }
        }

        if (!I('is_reservation'))
            unset($_GET['reservation_time']);

        if (!I('coupon_id'))
            unset($_GET['coupon_id']);

        //验证 前台计算的订单金额 与 后台计算的金额 是否相等
        $fee = I('fee');
        if (isset($fee))
            $order_amount_cal += $fee;//计算跑腿费 += 小费
//        dump('加小费后：'.$order_amount_cal);
        $is_have_price = I('is_have_price');
        $order_type = I('order_type');

        if ($order_type == 2 && $is_have_price == 1)
            $order_amount_cal += I('goods_amount');//计算跑腿费 += 代买商品金额
//        dump('加商品费：'.$order_amount_cal);
        $order_amount = floatval(I('real_amount'));


//        dump('前台real_amount:');
//        dump($order_amount);
//        dump('后台amount:');

        $order_amount_cal = floatval($order_amount_cal);
//        dump($order_amount_cal);

        if ( round($order_amount_cal,2) != round($order_amount,2)){//float类型比较函数，出现float(12.4) ！= float(12.4)的情况，这个函数避免 了这种情况
            return RET_NO_V(400, '订单金额计算有误，请重新下单');
        }//验证 ：前台计算的订单金额 ！= 后台计算的金额

//        exit;
        //订单支付记录
        if (3 == I('pay_method')) {
            $app_users = M('app_users')->where(array('user_id' => I('uid')))->field('purse_balance')->find();
            if ($app_users['purse_balance'] < $order_amount) {
                return RET_NO_V(400, "余额不足，请选择其它支付方式！");
            }
        }

        $this->order->startTrans();
        $order = $this->order->create(I('get.'));
        if ($order) {
            $ret = $this->order->add();
            if ($ret) {
                //优惠券ID
                $coupon_id = I('coupon_id');
                $user_coupon = M('user_coupon');
                //更改优惠券状态
                if (!empty($coupon_id)) {
                    if(!isvalid_used_coupon($coupon_id,I('uid')))
                        return RET_NO_V(400, "优惠券失效，请重新下单！");
//                    $user_coupon->startTrans();
                    $ret_user_coupon = $user_coupon->where(array('user_coupon_id' => $coupon_id, 'user_id' => I('uid')))->save(array('is_used' => 2,'used_orderid'=>$ret));
                    if (!$ret_user_coupon) {
                        //提交事务
//                        $user_coupon->commit();
//                    }else{
                        //事务回滚
//                        $user_coupon->rollback();
                        $this->order->rollback();
                        return RET_NO_V(400, "优惠券使用失败，请重试！");
                    }
                }

                $order_pay = M('order_pay');
                $datas = array(
                    'order_id' => $ret,
                    'pay_amount' => I('real_amount'),
                    'status' => 0,
                    'voucher_no' => I('voucher_no'),       //==商户唯一订单号
                    'pay_method' => I('pay_method')        //支付方式
                );
                $rets = $order_pay->add($datas);
                if ($rets) {
                    $otype = 0;
                    if (I('is_reservation') == 1)
                        $otype = 1;
                    $_GET['order_id'] = $ret;
                    $order_resmsm_db = M('order_resmsm');
                    $lat = "";
                    $lng = "";
                    switch (I('order_type')) {
                        //取送
                        case 1:
                            $lat = $send_latit;
                            $lng = $send_longit;
                            break;
                        //代买
                        case 2:
                            $lat = $reci_latit;
                            $lng = $reci_longit;
                            break;
                        //排队
                        case 3:
                            $lat = I('reci_latit');
                            $lng = I('reci_longit');
                            break;
                    }
                    $res_data = array('order_id' => $ret,
                        'company_id' => $order['company_id'],
                        'order_number' => $order['order_number'],
                        'order_type' => I('order_type'),
                        'app_user_id' => I('uid'),
                        'order_lat' => $lat,  //订单的纬度
                        'order_lng' => $lng,  //订单的经度
                        'order_time' => $order['order_time'],
                        'reservation_time' => I('reservation_time'),
                        'otype' => $otype,
                        'order_data' => json_encode(I('get.')));
                    if (!I('reservation_time'))
                        unset($res_data['reservation_time']);

                    $ret_res = $order_resmsm_db->add($res_data);
                    if ($ret_res) {
                        $this->order->commit();
                        return RET(200, "订单生成成功！", $ret);
                    } else {
                        $this->order->rollback();
                        return RET_NO_V(400, "订单临时表生成失败，请重试！");
                    }

                } else {
                    $this->order->rollback();
                    return RET_NO_V(400, "支付记录单生成失败，请重试！");
                }
            } else {
                $this->order->rollback();
                return RET_NO_V(400, "订单生成失败，请重试！");
            }
        } else {
            return RET_NO_V(400, $this->order->getError());
//            $this->error($this->order->getError());

        }

    }


    /**
     * 路径计算
     * {String} shippingLat 发货纬度
     * {String} shippingLng 发货经度
     * {String} collectLat 收货纬度
     * {String} collectLng 收货经度
     */
    function mapRoute()
    {
        $shippingLat = (double)I('shippingLat');
        $shippingLng = (double)I('shippingLng');
        $collectLat = (double)I('collectLat');
        $collectLng = (double)I('collectLng');
        $centerLat = ($shippingLat + $collectLat) / 2;
        $centerlng = ($shippingLng + $collectLng) / 2;

        $data = array(
            'shippingLat' => $shippingLat,
            'shippingLng' => $shippingLng,
            'centerLat' => $centerLat,
            'centerlng' => $centerlng,
            'collectLat' => $collectLat,
            'collectLng' => $collectLng,
        );

        $this->assign('route', $data);
        $this->display();

    }

    /**
     * 排队地址标注
     * {String} shippingLat 发货纬度
     * {String} shippingLng 发货经度
     */
    function lineUpmapRoute()
    {
        $shippingLat = (double)I('shippingLat');
        $shippingLng = (double)I('shippingLng');

        $data = array(
            'shippingLat' => $shippingLat,
            'shippingLng' => $shippingLng,
        );

        $this->assign('route', $data);
        $this->display();

    }

//    /**
//     * @api {get} userOrderRevaluate/order_id/:order_id/uid/:uid/token/:token/ratedValue/:ratedValue 用户给跑客评价
//     * @apiName 用户给跑客评价
//     * @apiGroup pt
//     *
//     * @apiParam {Int} uid 用户唯一ID.
//     * @apiParam {String} token 用户token,每次登录都会更改.
//     * @apiParam {Int} order_id 订单ID.
//     * @ratedValue {Int} ratedValue 评价的星星
//     **/
//    function userOrdeRevaluate()
//    {
//        $order = M('order');
//        //判断订单的归属人
//        $ret = $order->where(array('order_id' => I('order_id'), 'user_id' => I('uid')))->field('dispatch_id,disp_eval_value')->find();
//        if ($ret && empty($ret['disp_eval_value'])) {
//            $order->where(array('order_id' => I('order_id')))->save(array('disp_eval_value' => I('ratedValue')));
//            // 跑客好评处理
//            $status = pnPraise(I('ratedValue'), $ret['dispatch_id']);
//            //经验值处理
////            pnLevel(C('order_pn_exp'), $ret['dispatch_id']);
//
//
//
//
//            if ($status) {
//                RET_NO_V(0, "恭喜评价成功！");
//            } else {
//                RET_NO_V(1, "抱歉评价失败！");
//            }
//        } else {
//            RET_NO_V(1, "抱歉订单已经被评价过");
//        }
//    }


    /**
     * @api {get} modgetSMS/phone/:phone 修改后新手机号获取短信验证码
     * @apiName 修改后新手机号获取短信验证码
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} phone 手机号.
     **/

    function modgetSMS()
    {
        //接口权限校验
        verificationToken();
        $app_users = M('app_users');
        $user = $app_users->where(array('mobile' => I('phone')))->find();
        if (!$user) {
            $this->getSMS();
        } else {
            return RET_NO_V(408, "手机号已被占用");
        }

    }

    /**
     * 短信验证接口 467代表成功
     * @phone 手机号 必填
     * @code 验证码 必填
     */
    function checkcode_sms($mobile, $code)
    {
        if ($code == session('code')) {
            return RET_NO_V(200, "验证短信验证码成功！");
        } else {
            return RET_NO_V(1, "抱歉验证码错误，请重新获取");
        }
    }


    /**
     * @api {get} modCheckCode_sms/uid/:uid/token/:token 修改手机号时短信验证接口
     * @apiName 修改手机号时短信验证接口
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} phone 手机号 必填
     * @apiParam {Int} code 验证码 必填
     * @apiParam {Int} checkRandom 随机验证码 旧手机认证的时候不填 新手机认证必填
     */
    function modCheckCode_sms()
    {
        //接口权限校验
        verificationToken();
        $app_users = M('app_users');
        $rets = $app_users->where(array('user_id' => I('uid')))->field('validate_code')->find();
        if (!I('checkRandom')) {
            if (I('code') == session('code')) {
                $checkRandom = rand(000000, 999999);
                $ret = $app_users->where(array('user_id' => I('uid')))->save(array('validate_code' => $checkRandom));
                if ($ret) {
                    return RET(200, "校验成功", $checkRandom);
                } else {
                    return RET_NO_V(406, "校验失败");
                }
            } else {
                return RET_NO_V(1, "验证操作失败");
            }
        } else {
            if (I('checkRandom') == $rets['validate_code']) {
                if (I('code') == session('code')) {
                    //$app_users->where(array('user_id' => I('uid')))->save(array('validate_code' => null));
                    $ret = $app_users->where(array('user_id' => I('uid')))->save(array('mobile' => I('phone')));
                    if ($ret) {
                        return RET_NO_V(200, "更换手机号成功");
                    } else {
                        return RET_NO_V(400, "抱歉，更换失败");
                    }
                } else {
                    return RET_NO_V(1, "验证操作失败");
                }
            } else {
                return RET_NO_V(407, "校验失败");
            }
        }
    }

    /**
     * @api {get} modCheckCode_sms/uid/:uid/token/:token 请求保价或加急数据
     * @apiName 请求保价或加急数据
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} set_id 保价填1 加急填2必填
     */
    function supportValue()
    {
        $sys_set = M('sys_set');
        $ret = $sys_set->where(array('set_id' => I('set_id')))->field('collection_cost')->find();
        if ($ret) {
            return RET(0, "获取数据成功！", $ret);
        } else {
            return RET_NO_V(1, "获取数据失败！");
        }
    }


    /**
     * @api {get} userPurseBalance/uid/:uid/token/:token 获取用户余额
     * @apiName 获取用户余额
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *       "retCode": 0,
     *       "retDesc": "获取数据成功！"，
     *       "retValue":"2.00"
     *     }
     *
     * @apiError retCode=1为返回数据错误.
     *
     */
    function userPurseBalance()
    {
        //接口权限校验
        verificationToken();
        $user = M('user');
        $ret = $user->where(array('uid' => I('uid')))->field('purse_balance')->find();
        if ($ret) {
            return RET(0, "获取数据成功！", $ret);
        } else {
            return RET_NO_V(1, "获取数据失败！");
        }
    }

    //发送收货人随机码
    protected function sendMSMConsignee($tel, $order_id)
    {
        $client = new Client;
        $request = new SmsNumSend;


        //session("code", null);
        $code = $this->randString();

        $order = M('order');
        $ret = $order->where(array('order_id' => $order_id))->save(array('get_vali_code' => $code));
        if ($ret) {
            // 短信内容参数
            $smsParams = array(
                'code' => $code,
//            'product' => '帮你跑腿'
            );
            // 设置请求参数
            $req = $request->setSmsTemplateCode('SMS_12921226')
                ->setRecNum($tel)
                ->setSmsParam(json_encode($smsParams))
                ->setSmsFreeSignName('帮你跑腿')
                ->setSmsType('normal')
                ->setExtend('demo');
            $status = $client->execute($req);
            if ($status["alibaba_aliqin_fc_sms_num_send_response"]["result"]["success"]) {
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }

    }

    /**
     * 预约单 发送给用户和跑客，短信
     */
    public function orderReservationMSM()
    {

        $resmsm_db = M('order_resmsm r');

        $end_timer = strtotime('now');//获取当前时间的时间戳

        $setMinute = C('remind_minute');

        $minutes = $setMinute * 60;//时间戳减10分钟，配置文件中的设置

        $tmstart_timer = $end_timer - $minutes;
        $start_timer = date('Y-m-d H:i:s', $tmstart_timer);

        $resms = $resmsm_db->field('r.*,au.mobile as userTel,du.mobile as dispathTel')->where("is_send=0 and is_success = 0 and  reservation_time >='" . $start_timer . "' and  reservation_time <='" . date('Y-m-d H:i:s', time()) . "'")
            ->join('db_app_users au on au.user_id = r.app_user_id')
            ->join('db_dispatch du on du.dispatch_id = r.dispatch_id')
            ->select();
//        dump($resmsm_db->getLastSql());
        if (!$resms)
            return;

        foreach ($resms as $value) {
            $send_id = $value['send_id'];
            $userTel = $value['usertel'];
            $dispatchTel = $value['dispathtel'];
            $order_number = $value['order_number'];

            $userSend = $this->sendResMSM($userTel, '1', $order_number);
            $dispatchSend = $this->sendResMSM($dispatchTel, '2', $order_number);

            $data = array('is_send' => '1', 'is_success' => '1', 'send_time' => date('Y-m-d H-i-s', time()));
            $resmsm_db->where('send_id = ' . $send_id)->setField($data);

        }


    }

    /**
     * 发送预约提醒信息
     * @param $tel 电话
     * @param $userType 用户类型
     * @param $ordernum 订单号
     * @return int 1：发送成功，0：发送失败；2电话为空，3：用户类型为空 ，4：订单号为空
     */
    protected function sendResMSM($tel, $userType, $ordernum)
    {
        if (!$tel) {
            return 2;
        }
        if (!$userType || !is_numeric($userType) || intval($userType) > 3 || intval($userType) < 1) {
            return 3;
        }
        if (!$ordernum)
            return 4;

        $client = new Client;
        $request = new SmsNumSend;
        $proName = "帮你跑腿";
        $msmcode = "SMS_13280395";//跑腿

        if ($userType && $userType == 2)
            $msmcode = "SMS_13300476";

        // 短信内容参数
        $smsParams = array(
            'ordernum' => $ordernum,
        );

        // 设置请求参数
        $req = $request->setSmsTemplateCode($msmcode)
            ->setRecNum($tel)
            ->setSmsParam(json_encode($smsParams))
            ->setSmsFreeSignName($proName)
            ->setSmsType('normal');

        $status = $client->execute($req);

        if ($status["alibaba_aliqin_fc_sms_num_send_response"]["result"]["success"]) {

            return 1;
        } else {
            return 0;
        }

    }

    //发送注册验证码
    public function sendMSM($tel)
    {
        $client = new Client;
        $request = new SmsNumSend;
        //session("code", null);
        $code = $this->randString();
        // 短信内容参数
        $smsParams = array(
            'code' => $code,
            'product' => '帮你跑腿'
        );

        // 设置请求参数
        $req = $request->setSmsTemplateCode('SMS_12831629')
            ->setRecNum($tel)
            ->setSmsParam(json_encode($smsParams))
            ->setSmsFreeSignName('帮你跑腿')
            ->setSmsType('normal')
            ->setExtend('demo');

        $status = $client->execute($req);
        if ($status["alibaba_aliqin_fc_sms_num_send_response"]["result"]["success"]) {
            session("code", $code);
            return true;
        } else {
            return false;
        }

    }

    /**
     * 获取随机位数数字
     * @param  integer $len 长度
     * @return string
     */
    protected static function randString($len = 4)
    {
        $chars = str_repeat('0123456789', $len);
        $chars = str_shuffle($chars);
        $str = substr($chars, 0, $len);
        return $str;
    }


    /**
     * @api {get} alipayNotify 支付宝异步回调接口
     * @apiName 获取用户余额
     * @apiGroup pt
     *
     */
    public function alipayNotify()
    {

        vendor("pay_client_alipay.client_alipay");
        $pay = new \Payss();
        $rets = $pay->to_pay();
        logResult("支付数据post==" . json_encode($_POST));
        logResult("支付数据get==" . json_encode($_POST));
        $order_pay = M('order_pay');
        $out_trade_no = I('out_trade_no');
        $trade_no = I('trade_no');
        $pay_time = I('gmt_payment');
        $buyer_email = I('buyer_email');
        $trade_status = I('trade_status');

        if ($rets) {
            if ($trade_status == 'TRADE_FINISHED') {
            } else if ($trade_status == 'TRADE_SUCCESS') {
                $order_pay->startTrans();
                $pay_obj = $order_pay->where(array('voucher_no' => $out_trade_no))->find();
//                \Think\Log::record('status：'.$pay_obj['status']);
                if ($pay_obj['status'] == 0) {
                    $ret = $order_pay->where(array('voucher_no' => $out_trade_no))->save(array('pay_time' => $pay_time, 'pay_account' => $buyer_email, 'pay_number' => $trade_no, 'status' => 1));
                    $order_id = $order_pay->where(array('voucher_no' => $out_trade_no))->field('order_id')->find();
                    $order = M('order');
                    $retss = $order->where(array('order_id' => $order_id['order_id']))->save(array('pay_status' => 1, 'status' => 1));
                    $resmsm_ret = M('order_resmsm')->where(array('order_id' => $order_id['order_id']))->save(array('status' => 1, 'pay_status' => 1));//订单中间表状态修改

                    if ($retss && $ret && $resmsm_ret) {
                        $order_pay->commit();
                        echo "success";
                    } else {
                        $order_pay->rollback();
                        echo "fail";
                    }
                }else
                    echo "success";
            }
            echo "success";
        } else {
            $order_pay->where(array('voucher_no' => $out_trade_no))->save(array('pay_time' => $pay_time, 'pay_number' => $trade_no, 'status' => 2));
            echo "fail";
        }

    }

    /**
     * @api {get} weixinNotify 微信异步回调接口
     * @apiName 获取用户余额
     * @apiGroup pt
     *
     */
    public function weixinNotify()
    {
        vendor("WxpayAPI.WxPay");
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
//        \Think\Log::record('xml：'.$xml);
        $ret = xmlToArray($xml);

        $out_trade_no = $ret['out_trade_no'];

        //用户标识
        $openid = $ret['openid'];
        //微信订单号
        $transaction_id = $ret['transaction_id'];
        //交易结果
        $result_code = $ret['result_code'];//交易结果
        //total_fee
        $total_fee = $ret['total_fee'] / 100;//订单总金额，单位为分,除以100，单位换算为元
        $notify = new \WxPay();
        $data = array('transaction_id' => $transaction_id);//$ret['transaction_id']);//微信支付订单号
        $msg = "";
        $notify_ret = $notify->NotifyProcess($data, $msg);
        $user_recharge = M('user_recharge');
        $order_pay = M('order_pay');
        if ($notify_ret) {
            $result = $notify->Handle($result_code);
            if ($result_code == 'FAIL') {

            } else if ($result_code == 'SUCCESS') {
                $order_pay->startTrans();
                $pay_obj = $order_pay->where(array('voucher_no' => $out_trade_no))->find();
//                \Think\Log::record('status：'.$pay_obj['status']);
                if ($pay_obj['status'] == 0) {
                    $ret = $order_pay->where(array('voucher_no' => $out_trade_no))->save(array('pay_time' => date('Y-m-d H-i-s', time()), 'pay_account' => $openid, 'pay_number' => $transaction_id, 'status' => 1));
                    $order_id = $order_pay->where(array('voucher_no' => $out_trade_no))->field('order_id')->find();
                    $order = M('order');
                    $retss = $order->where(array('order_id' => $order_id['order_id']))->save(array('pay_status' => 1, 'status' => 1));
                    $resmsm_ret = M('order_resmsm')->where(array('order_id' => $order_id['order_id']))->save(array('status' => 1, 'pay_status' => 1));//订单中间表状态修改

                    if ($retss && $ret && $resmsm_ret) {
                        $order_pay->commit();
                        echo "SUCCESS";
                    } else {
                        $order_pay->rollback();
                        echo "FAIL";
                    }
                } else
                    echo "SUCCESS";

            }
            echo "SUCCESS";
        } else {
            $order_pay->where(array('voucher_no' => $out_trade_no))->save(array('pay_time' => date('Y-m-d H-i-s', time()), 'pay_number' => $transaction_id, 'status' => 2));
            echo "FAIL";
        }
    }

    /**
     * @api {get} alipayPayConfirm/uid/:uid/token/:token/tradeNO/:tradeNO 支付确认接口
     * @apiName 支付确认接口
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} tradeNO 客户端生成的商户订单号
     *
     * @apiSuccessExample 成功返回: 状态:0未支付，1成功，2失败
     *     HTTP/1.1 200 OK
     *     {
     *       "retCode": 0,
     *       "retDesc": "获取数据成功！"，
     *       "retValue":"0"
     *     }
     *
     * @apiError retCode=1为返回数据错误.
     *
     */
    public function alipayPayConfirm()
    {
        //接口权限校验
        verificationToken();
        $order_pay = M('order_pay');
        $ret = $order_pay->where(array('voucher_no' => I('tradeNO'), 'status' => 1))->find();
        if ($ret) {
            return RET(0, "获取状态成功!");
        } else {
            return RET_NO_V(1, "获取状态失败,请重试");
        }
    }


    /**
     * @api {get} orderShow/uid/:uid/token/:token/order_id/:order_id 获取用户订单详情
     * @apiName 获取用户订单详情
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} order_id 订单ID
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *          "retCode": 0,
     *          "retDesc": "获取成功!",
     *          "retValue": {
     *         }
     *     }
     *
     * @apiError retCode=1为返回数据错误.
     *
     */
    public function orderShow()
    {
        //接口权限校验
        verificationToken();
        $order = M("order");
        $order_pay = M("order_pay");
        $dispatch_db = M("dispatch");
        $user_coupon = M("user_coupon");
        $order_data = $order->where(array('order_id' => I('order_id'),'user_id' => I('uid')))->find();
//        echo $order->getLastSql();
//        dump($order_data);
        if($order_data)
        {
                if ($order_data['send_address_floor']) {
                    $order_data['send_address_floor'] = '(' . $order_data['send_address_floor'] . ')';
                }
                if ($order_data['reci_address_floor']) {
                    $order_data['reci_address_floor'] = '(' . $order_data['reci_address_floor'] . ')';
                }
                if ($order_data['coupon_id']){
                    $coupon_info = $user_coupon->where(array('user_coupon_id' => $order_data['coupon_id']))->field('coupon_type,coupon_value')->select(); 
                    
                    if($coupon_info){
                       if($coupon_info[0]["coupon_type"] == 1)
                       {
                           $coupon_value = $coupon_info[0]["coupon_value"];
                       }else{
                           $coupon_value = $order_data['order_amount'] - $order_data['real_amount'];
                       }
                    }
                }
               
                $pay_data = $order_pay->where(array('order_id' => I('order_id')))->field('voucher_no')->find();

                $dispatch_data = $dispatch_db->where(array('dispatch_id' => $order_data['dispatch_id']))->field('avatar,dispatch_name,mobile,praise')->find();
                $ret = array('order_data' => $order_data, 'pay_data' => $pay_data, 'dispatch_data' => $dispatch_data,'coupon_value'=>$coupon_value );
//                dump($ret);
                if ($ret) {
                    return RET(0, "获取订单数据成功!", $ret);
                } else {
                    return RET_NO_V(1, "数据查询失败!");
                }
        }else{
             return RET_NO_V(1, "非法数据操作!");
        }
    }

    /**
     * @api {get} createUser_recharge/uid/:uid/token/:token/recharge_amount/:recharge_amount/voucher_no/:voucher_no 用户充值记录表
     * @apiName 用户充值记录表
     * @apiGroup PN
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} order_id 订单ID
     * @apiParam {String} voucher_no 凭证号
     * @apiParam {String} recharge_amount 充值金额
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *          "retCode": 200,
     *          "retDesc": "充值记录生成成功"
     *     }
     *
     * @apiError retCode=400为返回充值记录生成失败.
     */
    function createUser_recharge()
    {
        //接口权限校验
        verificationToken();
        $mobile =I('mobile');
        $user_obj = M('app_users')->field('user_id')->where(array('mobile'=>$mobile))->find();
        if(!$user_obj){
            return RET_NO_V(400, '手机号有误，请重新收入');
        }

        $user_recharge = M('user_recharge');
        $data = array(
            'user_id' => $user_obj['user_id'],//用户id
            'recharge_amount' => I('recharge_amount'),//充值金额
            'status' => 0,//充值状态
            'voucher_no' => I('voucher_no'),//充值凭证号
            'pay_method' => I("pay_method"),
            'recharge_user_id'=>I('uid')//充值人
        );
        $ret = $user_recharge->add($data);
        if ($ret) {
            return RET_NO_V(200, '充值记录生成成功');
        } else {
            return RET_NO_V(400, '充值记录生成失败');
        }
    }

    /**
     * createUser_recharge 用户充值支付宝对接回调
     */
    function userAlipayPay()
    {

        vendor("pay_client_alipay.client_alipay");
        $pay = new \Payss();
        $rets = $pay->to_pay();
        //商户唯一订单号
        $out_trade_no = I('out_trade_no');
        //商户号
        $trade_no = I('trade_no');
        //支付时间
        $pay_time = I('gmt_payment');
        //支付账号
        $buyer_email = I('buyer_email');
        //支付状态
        $trade_status = I('trade_status');
        //用户余额表对象
        $user_recharge = M('user_recharge');
        if ($rets) {
            if ($trade_status == 'TRADE_FINISHED') {

            } else if ($trade_status == 'TRADE_SUCCESS') {
                $user_db=M('app_users');
                $user_db->startTrans();
                $user_recharge_ret = $user_recharge->where(array('voucher_no' => $out_trade_no))->find();
                if ($user_recharge_ret['status'] == 0) {
                    $give_money = give_money(I('total_fee'));
                    //===========修改充值记录信息 start =========
                    $ret = $user_recharge->where(array(
                        'voucher_no' => $out_trade_no
                    ))->save(array(
                        'pay_time' => $pay_time,
                        'pay_account' => $buyer_email,
                        'pay_number' => $trade_no,
                        'status' => 1,
                        'pay_method' => 1,
                        'give_money' => $give_money
                    ));
                    //===========修改充值记录信息 end =========
                    //1.是否有优惠，2.代充还是自充，3.是否送积分
                    //对应充值优惠策略
//                    if ($ret) {
//                        $user_recharge_obj = $user_recharge->where(array('voucher_no' => $out_trade_no))->field('recharge_record_id,user_id,recharge_amount,recharge_user_id')->find();
//                        $give_remark="";
//                        if($give_money && $give_money > 0)
//                            $give_remark="(充值" . $user_recharge_obj["recharge_amount"] . "元送" .$give_money . "元活动)";
//
//                        //==========处理代充值的消息 start===========
//                        $remark = "手机客户端通过支付宝成功充值" . $user_recharge_obj['recharge_amount'] . "元";
//                        if($user_recharge_obj['recharge_user_id'] && $user_recharge_obj['user_id'] != $user_recharge_obj['recharge_user_id'])// 代充
//                        {
//                            //给代充人发消息
//                            $rech_mobile = get_user_tel($user_recharge_obj['user_id']);//被充值的手机号
//                            $msg_remark= "您通过支付宝为手机号（".$rech_mobile."）成功充值".$user_recharge_obj['recharge_amount']."元";//充值的手机号的消息
//
//                            $reched_msg_ret = create_user_message($user_recharge_obj['recharge_user_id'], '代充值成功', $msg_remark, $msg_remark);
//
//                            //组织代充值的消息信息
//                            $reched_mobile = get_user_tel($user_recharge_obj['recharge_user_id']);//充值的手机号
//                            $remark = "手机号（".$reched_mobile."）在手机客户端通过支付宝为您充值" . $user_recharge_obj['recharge_amount'] . "元";//(充值" . $user_recharge_obj['recharge_amount'] . "元送" .$give_money . "元活动)，奖励您" . $points_value . "积分" ;
//                        }
//                        //==========处理代充值的消息 end===========
//
//                        //==========充值积分奖励 start cln20161203==========
//                        $points_value = 0.00;
//                        if (C('discount_points') && floatval(I('total_fee')) > 0.00)
//                            $points_value = round(C('discount_points') * I('total_fee'));
//                        $points_ret = 1;
//                        $points_msg_ret = 1;
//                        if ($points_value > 0) {
//                            $points_ret = addPoints(array('user_id' => $user_recharge_obj['user_id'], 'points_type' => 2, 'points_value' => $points_value, 'remark' => '支付宝充值积分奖励', 'from_id' => $out_trade_no));
//                            //发送充值送积分消息
//                            $point_msg_remark = $remark.$give_remark."，奖励您" . $points_value ."积分";
//                            $points_msg_ret = create_user_message($user_recharge_obj['user_id'], '充值送积分成功', $point_msg_remark, $point_msg_remark);
//                        }
//                        //==========充值积分奖励 end==========
//
//                        //==========处理用户表余额和用户钱包 start===========
//                        $Model = new \Think\Model();
//                        $retmoney = $user_recharge_obj['recharge_amount'] + $give_money;
//                        userPurseLog($user_recharge_obj['user_id'], 1, $user_recharge_obj['recharge_amount'] + $give_money,$remark.$give_remark, $user_recharge_obj['recharge_record_id'], 0);
//                        $retsss = $Model->execute("update db_app_users set purse_balance=purse_balance + " . $retmoney . " where user_id=" . $user_recharge_obj['user_id']);
//                        //新增用户钱包记录
//                        //==========处理用户表余额和用户钱包 end===========
//
//                        if ($retsss && $points_ret && $points_msg_ret) {
//                            $user_db->commit();
//                            echo "success";
//                        } else {
//                            $user_db->rollback();
//                            echo "fail";
//                        }
//                    } else {
//                        $user_db->rollback();
//                        echo "fail";
//                    }

                        echo "success";
                } else
                    echo "success";
            }
            echo "success";
        } else {
            $user_recharge->where(array('voucher_no' => $out_trade_no))->save(array('pay_time' => $pay_time, 'pay_number' => $trade_no, 'status' => 2));
            echo "fail";
        }
    }

    /**
     * createUser_recharge 用户充值微信对接回调
     * {"appid":"wx13b75a00b527e900","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id
        ":"1410034402","nonce_str":"2045000231","openid":"o5NUFwFM0OxJ_PNFy305s6ZmHT4k","out_trade_no":"CZ_TRADENO
     * 2016101711050146799","result_code":"SUCCESS","return_code":"SUCCESS","sign":"1B1D178799A9C93A8EAB703E6FA6F
     * 4AE","time_end":"20161117110058","total_fee":"1","trade_type":"APP","transaction_id":"40016320012016111799
     * 76195110"}
     * {"appid":"wx13b75a00b527e900","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1410034402"
     * ,"nonce_str":"fe2b421b8b5f0e7c355ace66a9fe0206","openid":"o5NUFwP_Mou-QZFgc56b3x_AEubo"
     * ,"out_trade_no":"CZ_TRADENO201610171535261051","result_code":"SUCCESS","return_code":"SUCCESS"
     * ,"sign":"87537B54E928A91125150816D961DC57","time_end":"20161117150213","total_fee":"1"
     * ,"trade_type":"APP","transaction_id":"4003392001201611170001347811"}
     */
    function useWeixinPay()
    {
        vendor("WxpayAPI.WxPay");
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
//        \Think\Log::record('xml：'.$xml);
        $ret = xmlToArray($xml);
        //商户唯一订单号
        $out_trade_no = $ret['out_trade_no'];
        //商户号
        $trade_no = $ret['mch_id'];
        //用户标识
        $openid = $ret['openid'];
        //微信订单号
        $transaction_id = $ret['transaction_id'];
        //交易结果
        $result_code = $ret['result_code'];//交易结果
        //total_fee
        $total_fee = $ret['total_fee'] / 100;//订单总金额，单位为分,除以100，单位换算为元

        $notify = new \WxPay();
        $data = array('transaction_id' => $transaction_id);//$ret['transaction_id']);//微信支付订单号
        $msg = "";
        $notify_ret = $notify->NotifyProcess($data, $msg);
        $user_recharge = M('user_recharge');
        if ($notify_ret) {
            $result = $notify->Handle($result_code);
//            \Think\Log::record('result：'.$result);
//            \Think\Log::record('测试日志信息'.json_encode($ret));
            if ($result_code == 'FAIL') {

            } else if ($result_code == 'SUCCESS') {
                $user_db=M('app_users');
                $user_db->startTrans();
                $user_recharge_ret = $user_recharge->where(array('voucher_no' => $out_trade_no))->find();
                if ($user_recharge_ret['status'] == 0) {
                    $give_money = give_money($total_fee);

                    $ret = $user_recharge->where(array(
                        'voucher_no' => $out_trade_no//商户订单号
                    ))->save(array(
                        'pay_time' => date('Y-m-d H-i-s', time()),//支付时间
                        'pay_account' => $openid,//支付账号
                        'pay_number' => $transaction_id, //支付流水号
                        'status' => 1,//状态:0未支付，1成功，2失败
                        'pay_method' => 2,//支付方式:1、支付宝，2微信
                        'give_money' => $give_money //赠送金额
                    ));
                    //对应充值优惠策略
//                    if ($ret) {
//                        $user_recharge_obj = $user_recharge->where(array('voucher_no' => $out_trade_no))->field('recharge_record_id,user_id,recharge_amount,recharge_user_id')->find();
//                        $give_remark="";
//                        if($give_money && $give_money > 0)
//                            $give_remark="(充值" . $user_recharge_obj["recharge_amount"] . "元送" .$give_money . "元活动)";
//
//                        //==========处理代充值的消息 start===========
//                         $remark = "手机客户端通过微信成功充值" . $user_recharge_obj['recharge_amount'] . "元";
//                        if($user_recharge_obj['recharge_user_id'] && $user_recharge_obj['user_id'] != $user_recharge_obj['recharge_user_id'])// 代充
//                        {
//                            //给代充人发消息
//                            $rech_mobile = get_user_tel($user_recharge_obj['user_id']);//被充值的手机号
//                            $msg_remark= "您通过微信为手机号（".$rech_mobile."）成功充值".$user_recharge_obj['recharge_amount']."元";//充值的手机号的消息
//                            $reched_msg_ret = create_user_message($user_recharge_obj['recharge_user_id'], $msg_remark, $msg_remark);
//
//                            //组织代充值的消息信息
//                            $reched_mobile = get_user_tel($user_recharge_obj['recharge_user_id']);//充值的手机号
//                            $remark = "手机号（".$reched_mobile."）在手机客户端通过微信为您充值" . $user_recharge_obj['recharge_amount'] . "元";//(充值" . $user_recharge_obj['recharge_amount'] . "元送" .$give_money . "元活动)，奖励您" . $points_value . "积分" ;
//                        }
//                        //==========处理代充值的消息 end===========
//                        //==========充值积分奖励 start cln20161203==========
//                        $points_value = 0.00;
//                        if (C('discount_points') && $total_fee > 0.00)
//                            $points_value = round(C('discount_points') * $total_fee);//获取要增加的积分
//                        $points_ret = 1;
//                        $points_msg_ret = 1;
//                        if ($points_value > 0) {
//                            $points_ret = addPoints(array('user_id' => $user_recharge_obj['user_id'], 'points_type' => 2, 'points_value' => $points_value, 'remark' => '微信充值积分奖励', 'from_id' => $out_trade_no));
//
//                            $point_msg_remark = $remark.$give_remark."，奖励您" . $points_value ."积分";
//                            $points_msg_ret = create_user_message($user_recharge_obj['user_id'], '充值送积分成功', $point_msg_remark, $point_msg_remark);
//                         }
//
//                        //==========充值积分奖励 end==========
//                        //==========处理用户表余额和用户钱包 start===========
//                        $Model = new \Think\Model();
//                        $retmoney = $user_recharge_obj['recharge_amount'] + $give_money;
//                        //新增用户钱包记录
//                        userPurseLog($user_recharge_obj['user_id'], 1, $user_recharge_obj['recharge_amount'] + $give_money,$remark.$give_remark, $user_recharge_obj['recharge_record_id'], 0);
//                        $retsss = $Model->execute("update db_app_users set purse_balance=purse_balance + " . $retmoney . " where user_id=" . $user_recharge_obj['user_id']);//修改用户表余额
//                        //==========处理用户表余额和用户钱包 end===========

//                        if ($retsss && $points_ret && $points_msg_ret) {
////                        echo "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
//                            $user_db->commit();
//                            echo $result;
//                        } else {
//                            $user_db->rollback();
//                            echo $result;
//                        }
//                    } else {
//                        $user_db->rollback();
//                        echo $result;
//                    }
                } else {
                    echo $result;
                }
            }
            echo $result;
        } else {
//            \Think\Log::record('验证失败！');
            $user_recharge->where(array('voucher_no' => $out_trade_no))->save(array('pay_time' => date('Y-m-d H-i-s', time()), 'pay_number' => $transaction_id, 'status' => 2));
            echo "FAIL";
        }
    }


    /**
     * @api {get} userAlipayPayConfirm/uid/:uid/token/:token/ 用户充值确认
     * @apiName 用户充值确认
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} voucher_no 凭证号（商户订单唯一ID）.
     *
     **/

    function userAlipayPayConfirm()
    {
        //接口权限校验
        verificationToken();
        $user_recharge = M("user_recharge");
        $ret = $user_recharge->where(array('voucher_no' => I('voucher_no')))->field('pay_method,user_id,status,recharge_amount,recharge_record_id,give_money,recharge_user_id')->find();
//        dump($ret);

        if ($ret['status'] && $ret['status'] == "1") {
            if($ret['pay_method']==='1')
                $pay_method = '支付宝';
            else
                $pay_method = '微信';
            $give_money = $ret['give_money'];
            $give_remark="";
            if($give_money && $give_money > 0)
                $give_remark="(充值" . $ret["recharge_amount"] . "元送" .$ret['give_money'] . "元活动)";

            $user_recharge->startTrans();
            //==========处理代充值的消息 start===========
            $remark = "手机客户端通过".$pay_method."成功充值" . $ret['recharge_amount'] . "元";
            if($ret['recharge_user_id'] && $ret['user_id'] != $ret['recharge_user_id'])// 代充
            {
                //给代充人发消息
                $rech_mobile = get_user_tel($ret['user_id']);//被充值的手机号
//                dump('被充值的手机号:'.$rech_mobile);
                $msg_remark= "您通过".$pay_method."为手机号（".$rech_mobile."）成功充值".$ret['recharge_amount']."元";//充值的手机号的消息
//                dump('代充，给充值人发系统消息：'.$msg_remark);

                $reched_msg_ret = create_user_message($ret['recharge_user_id'],'代充值成功', $msg_remark, $msg_remark);
//                dump('消息结果:'.$reched_msg_ret);
                //组织代充值的消息信息
                $reched_mobile = get_user_tel($ret['recharge_user_id']);//充值的手机号
//                dump('充值的手机号:'.$rech_mobile);
                $remark = "手机号（".$reched_mobile."）在手机客户端通过".$pay_method."为您充值" . $ret['recharge_amount'] . "元";//(充值" . $user_recharge_obj['recharge_amount'] . "元送" .$give_money . "元活动)，奖励您" . $points_value . "积分" ;
                if(!$reched_msg_ret){
                    $user_recharge->rollback();
                    return RET(1, '代充值消息写入失败！');
                }
            }

            //==========处理代充值的消息 end===========
            //==========充值积分奖励 start cln20161203==========
            $points_value = 0.00;
            if (C('discount_points') && $ret['recharge_amount'] > 0.00)
                $points_value = round(C('discount_points') * $ret['recharge_amount']);//获取要增加的积分
//            dump($points_value);
            if ($points_value > 0) {
                $point_remark = $remark."，奖励您" . $points_value ."积分";
                $points_ret = addPoints(array('user_id' => $ret['user_id'], 'points_type' => 2, 'points_value' => $points_value, 'remark' => $point_remark, 'from_id' =>  I('voucher_no')));
//                dump('赠积分结果：:'.$points_ret);
                $point_msg_remark = $remark.$give_remark."，奖励您" . $points_value ."积分";
                $points_msg_ret = create_user_message($ret['user_id'], '充值送积分成功', $point_msg_remark, $point_msg_remark);
//                dump('赠积分发系统消息的结果：:'.$points_msg_ret);
                if(!$points_ret || !$points_msg_ret){
                    $user_recharge->rollback();
                    return RET(1, '积分消息写入失败！');
                }
            }

            //==========充值积分奖励 end==========
            //==========处理用户表余额和用户钱包 start===========
            $Model = new \Think\Model();
            $retmoney = $ret['recharge_amount'] + $give_money;
            //新增用户钱包记录
            $purse_log = userPurseLog($ret['user_id'], 1, $ret['recharge_amount'] + $give_money,$remark.$give_remark, $ret['recharge_record_id'], 0);
//            dump('新增用户钱包记录的结果：:'.$points_msg_ret);
            $retsss = $Model->execute("update db_app_users set purse_balance=purse_balance + " . $retmoney . " where user_id=" . $ret['user_id']);//修改用户表余额
            //==========处理用户表余额和用户钱包 end===========

            $user_id = $ret['user_id'];
            if($ret['recharge_user_id'] && $ret['recharge_user_id'] != $ret['user_id'])
                $user_id = $ret['recharge_user_id'];
            $rets = M('app_users')->where(array('user_id' =>$user_id))->field('purse_balance')->find();//返回的是登录人的余额
//            dump('充值返回的结果：:'.$rets);
            if ($purse_log && $retsss && $rets) {
                return RET(0, '用户充值成功！', $rets['purse_balance']);
            } else {
                return RET_NO_V(1, '用户充值成功！，获取余额失败！');
            }
        } else {
            return RET_NO_V(1, '用户充值失败！');
        }
    }

    /**
     * @api {get} userRechargeLog/token/:token/uid/:uid/ 用户充值记录
     * @apiName 用户充值记录
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     *
     **/
    function userRechargeLog()
    {
        //接口权限校验
        verificationToken();
        $user_purse = M("user_purse");
        $count = $user_purse->where(array('user_id' => I('uid')))->count();
        $ret = $user_purse->where(array('user_id' => I('uid')))->field('purse_amount,change_time,change_remark,purse_type')->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->order('change_time desc')->select();
        $rets['data'] = $ret;
        $rets['count'] = ceil($count / I("pagenum"));
        if ($ret) {
            return RET(0, '获取用户资金记录成功！', $rets);
        } else {
            return RET_NO_V(1, '获取用户资金记录失败！');
        }
    }


    /**
     * @api {get} PnUserLogin/mobile/:mobile/validate_code/:validate_code/ 【跑客端】用户登录
     * @apiName 【跑客端】用户登录
     * @apiGroup PN
     *
     * @apiParam {Int} mobile 用户手机号.
     * @apiParam {Int} validate_code 短信验证码.
     **/
    function pnUserLogin()
    {
        $mobile = I("mobile");
        $validate_code = I("validate_code");
        if ($mobile == 18538512653 && $validate_code == 1234) {
            $dispatch_db = M('dispatch');
            //跑哪级别表
            $dispatch_level = M("dispatch_level");
            //跑客运输工具表
            $conveyance = M("conveyance");
            $ret = $dispatch_db->where(array('mobile' => $mobile))->find();
            $ret['leval'] = $dispatch_level->where(array('dispatch_level_id' => $ret['dispatch_level_id']))->field('level_name,level_img')->find();
            $ret['conveyance'] = $conveyance->where(array('conveyance_id' => $ret['conveyance_id']))->field('conv_name')->find();
            return RET(0, "登录成功", $ret);
        } else {
            if ($validate_code == session('code')) {
                if (!$mobile || !$validate_code) {
                    return RET_NO_V(2, "手机号或验证码未填写");
                }
                $dispatch = M("dispatch");
                $dispatch->startTrans();
                //==================如果已经注册过================================
                $dis = $dispatch->where(array('mobile' => $mobile))->field('mobile,account_status,freeze_time,freeze_reason,first_login_time')->find();
                if ($dis) {
//                    if (3 == $dis['account_status']) {
//                        $freeze = "您的账号异常，请联系客服";
//                        return RET_NO_V(1, $freeze);
//                    } else
                    if (3 == $dis['is_sign']) {
                        return RET_NO_V(1, "您的账户已解约，不能登录！");
                    }
                    //==========第一次登陆时间========
                    $first_login_time = $dis['first_login_time'];
                    if (!$first_login_time)
                        $first_login_time = date('Y-m-d H:i:s', time());

                    //===============更新手机号信息=========================================
                    $rets = $dispatch->where(array('mobile' => $mobile))->save(array('validate_code' => $validate_code, 'token' => md5(uniqid(rand())), 'last_login_time' => date('Y-m-d H:i:s', time()), 'first_login_time' => $first_login_time));

                    if ($rets) {
                        $ret = $dispatch->where(array('mobile' => $mobile))->find();
                        //跑哪级别表
                        $dispatch_level = M("dispatch_level");
                        //跑客运输工具表
                        $conveyance = M("conveyance");
                        //推荐关系表
                        $recommend = M('recommend');

                        //获取推荐表此人是否是未激活状态
                        $recommend_status = $recommend->where(array('recommended_person_id' => $ret['dispatch_id'], 'recommended_person_type' => 2, 'recommended_status' => 0))->field('recommend_id,recommended_status,recom_person_id,recom_person_type,recommended_person_id')->find();
                        //如果为推荐的人
                        if ($recommend_status) {
                            $reco_ret = $recommend->where(array('recommend_id' => $recommend_status['recommend_id']))->save(array('recommended_status' => 1));
                            if ($reco_ret) {
                                if ($recommend_status['recom_person_type'] == 1) {
                                    $msg_ret = create_user_message($recommend_status['recom_person_id'], '推荐跑客注册登录成功', '恭喜您！推荐跑客注册登录成功', '恭喜您！推荐跑客注册登录成功');

                                    //==================推荐新用户有礼 start===============
//                                    $rand = rand(1, 3);
//                                    if ($rand == 1)
//                                        $rand_key = 'S7Rz6VbZHeNy7NrB';
//                                    else if ($rand == 2)
//                                        $rand_key = 'ecnnL%Oywj7#j6X!';
//                                    else if ($rand == 3)
//                                        $rand_key = '19^T6QsQneyES@w9';
//
//                                    $rand_ret = newuser_reward_coupon2($recommend_status['recom_person_id'], $rand_key, $recommend_status['recommended_person_id']);//奖励推荐人优惠券
//
//                                    if (1 == $rand_ret && $msg_ret) {
//                                        //优惠券发放成功发消息
//                                        $coupon_info = M("coupon_info");
//                                        $cou_ret = $coupon_info->field('coupon_value')->where("coupon_key='" . $rand_key . "' and is_push=1 and surplus_num >=0")->find();
//                                        $user_msg_ret = create_user_message($recommend_status['recom_person_id'], '推荐新跑客注册登录成功有礼', '随机奖励' . $rand . '元优惠券已发放给您', '随机奖励' . $rand . '元优惠券已发放给您');
//
//                                        if (!$user_msg_ret || !$cou_ret) {//调用方法，返回  0失败 roll，其他值不管
//                                            $dispatch->rollback();
//                                            return RET_NO_V(1, "推荐有误，请稍后再试");
//                                        }
//                                    } elseif (!$rand_ret || !$msg_ret) {//调用方法，返回  0失败 roll，其他值不管
//                                        $dispatch->rollback();
//                                        return RET_NO_V(1, "推荐有误，请稍后再试");
//                                    }
                                } elseif ($recommend_status['recom_person_type'] == 2) {
                                    $msg_ret = create_dispatch_message($recommend_status['recom_person_id'], '推荐跑客注册登录成功', '恭喜您！推荐跑客注册登录成功', '恭喜您！推荐跑客注册登录成功');

//                                    $rand = rand(1, 2);
//                                    //增加余额，增加推荐奖励金额
//                                    $user_db = M('dispatch');
//                                    $user_purse = $user_db->where(' dispatch_id = ' . $recommend_status['recom_person_id'])->field('cash_balance,recommend_amount')->find();
//                                    $cash_balance = floatval($user_purse['cash_balance']) + $rand;//推荐人的账户金额
//                                    $recommen_count = floatval($user_purse['recommend_amount']) + $rand;//推荐人的推荐金额
//                                    $dispatch_ret = $user_db->where('dispatch_id=' . $recommend_status['recom_person_id'])->setField(array('recommend_amount' => $recommen_count, 'cash_balance' => $cash_balance));
//                                    //跑客钱包表
//                                    $balance_ret = create_dispatch_balance($recommend_status['recom_person_id'], 5, $rand, 0, '推荐跑客注册登录成功，随机奖励' . $rand . '元');
//                                    //发送推荐奖励消息
//                                    $dismsg_ret = create_dispatch_message($recommend_status['recom_person_id'], '推荐新跑客注册登录成功有礼', '随机奖励' . $rand . '元已存入您的账户', '随机奖励' . $rand . '元已存入您的账户');
//
//                                    if (!$msg_ret || !$dispatch_ret || !$balance_ret || !$dismsg_ret) {
//                                        $dispatch->rollback();
//                                        return RET_NO_V(1, "推荐有误，请稍后再试");
//                                    }
                                }
                                //==================推荐新用户有礼 end===============
                                $upmsg_ret = login_upmsg_sys($ret['dispatch_id'], 2);//新用户系统消息 信息
                                $dispatch->commit();
                                $ret['leval'] = $dispatch_level->where(array('dispatch_level_id' => $ret['dispatch_level_id']))->field('level_name,level_img')->find();
                                $ret['conveyance'] = $conveyance->where(array('conveyance_id' => $ret['conveyance_id']))->field('conv_name')->find();
                                return RET(0, "登录成功", $ret);
                            } else {
                                $dispatch->rollback();
                                return RET_NO_V(1, "激活失败，请稍后再试");
                            }
                        } else {
                            $upmsg_ret = login_upmsg_sys($ret['dispatch_id'], 2);//更新老用户系统消息 信息
                            $dispatch->commit();
                            $ret['leval'] = $dispatch_level->where(array('dispatch_level_id' => $ret['dispatch_level_id']))->field('level_name,level_img')->find();
                            $ret['conveyance'] = $conveyance->where(array('conveyance_id' => $ret['conveyance_id']))->field('conv_name')->find();
                            return RET(0, "登录成功", $ret);

                        }

                    } else {
                        $dispatch->rollback();
                        return RET_NO_V(1, "登录失败，请稍后再试");
                    }
                } else {
                    //==================如果未注册过================================
                    $ret = $dispatch->add(array('mobile' => $mobile, 'company_id' => 4, 'avatar' => 'Uploads/public/icon.png', 'is_audit' => 0, 'is_incubator' => 0, 'evaluate_star' => 0, 'growth_value' => 0, 'dispatch_level_id' => 1, 'cash_balance' => 0.00, 'city_id' => 128, 'token' => md5(uniqid(rand())), 'first_login_time' => date('Y-m-d H:i:s', time()), 'last_login_time' => date('Y-m-d H:i:s', time())));
                    if ($ret) {
                        $ret = $dispatch->where(array('dispatch_id' => $ret))->find();
                        $dispatch_level = M("dispatch_level");
                        $ret['leval'] = $dispatch_level->where(array('dispatch_level_id' => $ret['dispatch_level_id']))->field('level_name,level_img')->find();
                        $upmsg_ret = login_upmsg_sys($ret, 2);//新用户--系统消息 信息
                        $dispatch->commit();
                        return RET(0, "登录成功", $ret);
                    } else {
                        $dispatch->rollback();
                        return RET_NO_V(1, "登录失败，请稍后再试");
                    }

                }

            } else {
                return RET_NO_V(3, "抱歉验证码错误，请重新获取");
            }
        }
    }

    /**
     * @api {get} pnOrderAmount/uid/:uid/token/:token/ 【跑客端】首页数据接口
     * @apiName 【跑客端】首页数据接口
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客id.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * {
     *     "retCode": 200,
     *     "retDesc": "获取成功",
     *     "retValue": {
     *          "todayordernum": "3", 今日的单数
     *          "todayMoneyNum": 29.6,  今日已赚取金额
     *          "onlinetime": 在线时长
     *         "totalmileage": 总里程
     *          "totalMoneyNum":财力值
     *          "comp_order_num":战力
     *          "job_number":工号
     *           "evaluate_star":魅力值
     *           "praise":好评率
     *           "growth_value":经验
     *           "level_name":用户名
     *           "onlinetime":总在线时长
     *            "totalmileage":总里程
     *            "todaytime":今日在线时长
     *            "serv_charge_rate"：佣金比例
     *          "countNotEnd": {
     *                  {
     *                     "send_address":发件人地址
     *                      "reci_address"收件人地址
     *                  }
     *
     *          }
     *       }
     * }
     */
    function pnOrderAmount()
    {
        //跑客端接口权限校验
        //pnerificationToken();
        $order = M('order');
        //$message = M('message');
        $dispatch = M('dispatch');
        $dispatch_balance = M('dispatch_balance');
        $date = date('Y-m-d') . '%';
        $where['dispatch_id'] = array('eq', I('uid'));
        $where['status'] = array('eq', 7);
        $where['dispatch_end_time'] = array('like', $date);

        $map['dispatch_id'] = I('uid');
        $map['time'] = array('like', $date);
        $ret = array();
        $ret_balance = $dispatch_balance->where($map)->field('balance_amount,balance_type')->select();
        $dayCount = 0;
        if ($ret_balance) {
            for ($i = 0; $i < count($ret_balance); $i++) {
                if ($ret_balance[$i]['balance_type'] == 1 || $ret_balance[$i]['balance_type'] == 3 || $ret_balance[$i]['balance_type'] == 5 || $ret_balance[$i]['balance_type'] == 10) {
                    $dayCount += $ret_balance[$i]['balance_amount'];
                }
            }
        }
        //当月的财力值
        $ret_val = $dispatch_balance->where(array('dispatch_id' => I('uid'),'time'=>array('like'=>date('Y-m-d') . '%')))->field('balance_amount,balance_type')->select();

        $Count = 0;
        if ($ret_val) {
            for ($i = 0; $i < count($ret_val); $i++) {
                if ($ret_val[$i]['balance_type'] == 1 || $ret_val[$i]['balance_type'] == 3 || $ret_val[$i]['balance_type'] == 5 || $ret_val[$i]['balance_type'] == 10) {
                    $Count += $ret_val[$i]['balance_amount'];
                }
            }
        }

        $ret['todayMoneyNum'] = number_format($dayCount, 2);//今日赚取总金额
        $ret['totalMoneyNum'] = number_format($Count, 2);//财力值

        $num = 0;
        $todayordernum = $order->where($where)->field('order_amount')->count();
        $where['status'] = array('between', '2,6');
        $orderNotEnd = $order->where($where)->select();
        $countNotEnd = 0;
//        $ret['countNotEnd'] = null;
//        if ($orderNotEnd) {
//            $countNotEnd = count($orderNotEnd);
//            $ret['countNotEnd'] = $countNotEnd;
//            for ($i = 0; $i < $countNotEnd; $i++) {
//                $ret['countNotEnd'][$i]['send_address'] = $orderNotEnd[$i]['order_amount']['sen   d_address']; //未完成单子发货地址
//                $ret['countNotEnd'][$i]['reci_address'] = $orderNotEnd[$i]['order_amount']['reci_address'];//未完成单子收货地址
//            }
//        }

        $todayordernum += $countNotEnd;
        $ret['todayordernum'] = $todayordernum; //今日接单总量

        //查询用户@place_up_time最后的更新位置，@todaytime今日在线时长，@onlinetime在线时间
        $dispatch_time = $dispatch->where(array('dispatch_id' => I('uid')))->field('place_up_time,todaytime,onlinetime')->find();
        //判断是位置信息是否是今天的时间
        if (substr($dispatch_time['place_up_time'], 0, 10) != date('Y-m-d')) {
            //如果是则更新今日在线时长+1
            $dispatch->where(array('dispatch_id' => I('uid')))->save(array('todaytime' => 0));
        }

        $rets = $dispatch->where(array('dispatch_id' => I('uid')))->field('totalmileage,growth_value,praise,todaytime,onlinetime,place_up_time,job_number,dispatch_level_id,comp_order_num,order_model,accumulatemoney,evaluate_star,dispatch_name,avatar,mobile,is_audit,company_id')->find();
        $retss = M('dispatch_level')->where(array('dispatch_level_id' => $rets['dispatch_level_id']))->field('level_name,serv_charge_rate')->find();

        $ret_status = login_upmsg_sys(I('uid'), 2);
        $msg_count = "";
        if ($ret_status) {
            $msg_count = getmsg_sys_unread(I('uid'), 2);
        }
        if ($rets['job_number'] === false) {
            $rets['job_number'] = "暂无工号";
        }

        //当月的战力值（完成单数）和魅力值（星星数）
        $thisMonthOrderCount = getThisMonthOrderCount(I('uid'));
        $ret['comp_order_num'] = $thisMonthOrderCount['order_count']; //战力
        $ret['dispatch_name'] = $rets['dispatch_name']; //跑客姓名
        $ret['avatar'] = $rets['avatar']; //跑客头像
        $ret['mobile'] = $rets['mobile']; //跑客手机号
        $ret['job_number'] = $rets['job_number'];    //工号
        $ret['is_audit'] = $rets['is_audit'];       //审核状态
        $ret['audit_deac'] = is_audit_status($rets['is_audit']); //审核描述
        $ret['todaytime'] = $rets['todaytime'];    //今日在线时长
        $ret['evaluate_star'] = $thisMonthOrderCount['user_eval_value'];           //魅力值
        $ret['praise'] = $rets['praise'];     //好评率
        $ret['growth_value'] = $rets['growth_value']; //经验
        $ret['serv_charge_rate'] = $retss['serv_charge_rate'];    //提取佣金比例
        $ret['level_name'] = $retss['level_name'];    //用户名
        //$ret['onlinetime'] = round($rets['onlinetime']/60,2);    //总在线时长
        $ret['onlinetime'] = $rets['onlinetime'];    //总在线时长
        $ret['totalmileage'] = $rets['totalmileage']; //总里程
        $ret['company_id'] = $rets['company_id'];//公司ID
        $ret['team_name'] = team_name($rets['company_id']); //所属团队
        $ret['order_model'] = $rets['order_model'];     //接单模式
        $ret['msg_count'] = $msg_count;
        //$ret['message'] = $message->where(array('message_type' => 2))->limit(4)->order('send_time Desc')->select();
        return RET(200, "获取成功", $ret);
    }

    /**
     * @api {get} pnRobOrder/voucher_no/:voucher_no/uid/:uid/dispatch_get_money/:dispatch_get_money 【跑客端】接单
     * @apiName 【跑客端】接单
     * @apiGroup PN
     *
     * @apiParam {Int} voucher_no .
     * @apiParam {Int} dispatch_id 跑客ID.
     **/
    function pnRobOrder()
    {
        //跑客端接口权限校验
        pnerificationToken();
        $order = M('order');
        $order_pay = M('order_pay');
        //反查得到order_id
        $order_id = $order_pay->where(array('voucher_no' => I('voucher_no')))->field('order_id')->find();
//        dump($order_id);
        //查出来指定的订单ID，并且是待分配的
        $rets = $order->where(array('order_id' => $order_id['order_id']))->find();
        if (1 == $rets['status']) {
            //抢单人员的策略在此执行
            //1.抢单人员必须提交了相关资料（db_dispatch中is_audit为2）
            $dispatch = M('dispatch');
            //查询派单员是否审核通过
            $retdis = $dispatch->where(array('dispatch_id' => I('uid')))->field('is_audit,is_test,is_sign,account_status,cash_balance,order_count')->find();
            //判断派单员的审核状态
            //是否审核通过(0 未提交审核 1已提交审核，2已经审核通过 3审核未通过)
            switch ($retdis['is_audit']) {
                case 0:
                    //抱歉您未进行身份认证
                    RET_NO_V(1, "抱歉，您未进行身份认证");
                    break;
                case 1:
                    //身份认证资料正在进行中
                    RET_NO_V(1, "身份认证资料正在进行中");
                    break;
                case 2:

                    if ($retdis['is_sign'] != 2) {
                        RET_NO_V(1, "您未进行培训，请联系客服参加培训");
                        break;
                    }
                    if ($retdis['account_status'] == 2 || $retdis['account_status'] == 3) {
                        RET_NO_V(1, "您的账号暂时冻结或停用，请联系客服解除后方可接单");
                        break;
                    }


                    //即时单可以接1单，预约单可以接多单
                    //预约单时间控制：取送代买的，是预约时间3个小时之后可以再接预约单；排队单是排队结束后可以再接预约单。
                    //$rets['is_reservation']=0,新单为即时单，$rets['is_reservation']=1，新单为预约单
                    if ($rets['is_reservation'] == 0) {//新单为即时单
                        $count = $order->where('dispatch_id=' . I('uid') . ' and status>1 and status<7 and is_reservation=0')->count();
                        if ($count >= $retdis['order_count']) {
                            return RET_NO_V(1, "您已经有足够的任务啦");
                            break;
                        }
                    } elseif ($rets['is_reservation'] == 1) {//新单为预约单
                        $reservation_count = $order->where('dispatch_id=' . I('uid') . ' and status>1 and status<7 and is_reservation=1')->count();
                        if ($reservation_count > 0) {
                            return RET_NO_V(1, "您已经有预约任务了，您现在只能接收即时任务");
                        }

                    }


                    //即时单可以接1单，预约单可以接多单 15638506782
                    //预约单时间控制：取送代买的，是
//                    $count = $order->where('dispatch_id=' . I('uid') . ' and status>1 and status<7')->count();
//                    //如果进行中的单子有一单
//                    if ($count == 1) {
//                        //查询是否有预约单
//                        $order_count = $order->where('dispatch_id=' . I('uid') . ' and status>1 and status<7')->field('is_reservation')->find();//
//                        //是一单即时单
//                        if ($order_count['is_reservation'] == 0) {
//                            if ($rets['is_reservation'] == 0) {
//                                return RET_NO_V(1, "您已经有即时任务了，您现在只能接收预约任务");
//                                break;
//                            }
//                        } else {
//                            if ($rets['is_reservation'] == 1) {
//                                return RET_NO_V(1, "您已经有预约任务了，您现在只能接收即时任务");
//                                break;
//                            }
//                        }
//                    } else if ($count == 2) {
//                        return RET_NO_V(1, "您已经有足够的任务啦");
//                        break;
//                    }

                    $order->startTrans();
                    //============================
                    //暂时取消 ===每天首单扣除保险费 2016-12-29 18:55:14
//                    $insu_ret = save_dispatch_insurance(I('uid'), $order_id['order_id'], 2);
//                    $insu_ret = dispatch_insurance_options(I('uid'), $order_id['order_id'], -2, 6, '扣除保险费', '每天首次接单扣除保险费2.00元', '您今天首次接单（' . $rets['order_number'] . '）扣除保险费2.00元');
//                    dump($insu_ret);
                    //if (0 == $insu_ret) {
                    //    $order->rollback();
                    //    RET_NO_V(1, "跑客首单保险费扣除失败");
                    //    break;
                    //}
                    //=====================
                    //此派单员已经签约通过，进行订单更改和抢单操作
                    $ret = $order->where(array('order_id' => $order_id['order_id']))->save(array(
                        //更改单子的抢单状态
                        'status' => 2,
                        //派单员ID更新
                        'dispatch_id' => I('uid'),
                        //更改单子抢单最后时间
                        'dispatch_end_time' => date('Y-m-d H:i:s'),
                        'dispatch_get_money' => I('dispatch_get_money')
                    ));

                    $order_upret = M('order_resmsm')->where(array('order_id' => $order_id['order_id']))
                        ->setField(array('status' => '2', 'dispatch_id' => I('uid')));

                    //判断抢单是否成功
                    if ($ret) {
                        //抢单成功
//                        if(0 == $rets['is_reservation']){
//                            $rems_db = M('order_resmsm');
//                            $del_ret = $rems_db->where('order_id='.$order_id['order_id'].' and otype=0')->delete();
//                            if(!$del_ret){
//                                $order->rollback();
//                                return RET_NO_V(1, "接单中操作失败，请稍后");
//                            }
//                        }

                        //$insu_ret=1成功，则写入用户消息
                        $msg_ret = create_user_message($rets['user_id'], '订单已被接收', '订单（' . $rets['order_number'] . '）已被接收', '您的订单（' . $rets['order_number'] . '）已被跑客接收，即刻为您完成');
                        rob_order_push($rets['user_id'], '订单（' . $rets['order_number'] . '）已被接收',array());//用户端极光推送

                        if (!$msg_ret) {
                            $order->rollback();
                            return RET_NO_V(1, "插入用户消息失败");
                        } else {
                            $order->commit();
                            return RET_NO_V(0, "接单成功");
                        }
                    } else {
                        //抢单失败
                        $order->rollback();
                        return RET_NO_V(1, "接单失败");
                    }
                    break;
                case 3:
                    //身份资料审核未通过
                    RET_NO_V(1, "身份资料审核未通过");
                    break;
                default:
                    RET_NO_V(1, "认证异常");
                    break;
            }
        } else if (9 == $rets['status']) {
            RET_NO_V(2, "订单已取消！");
        } else {
            RET_NO_V(2, "已经有人抢单！");
        }
    }

    /**
     * @api {get} pnOrderState/uid/:uid/token/:token/ 【跑客端】未完成订单状态
     * @apiName 【跑客端】未完成订单状态
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客id.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * {
     *    "retCode": 200,
     *    "retDesc": "获取成功",
     *    "retValue": {
     *         "order_id":"订单id"
     *        "send_address": "发件人地址",
     *        "reci_address": "收件人地址",
     *        "order_time": "订单下单时间",
     *        "order_amount": "订单金额"
     *    }
     * }
     * @apiError retCode=401为返回无未完成订单.
     */
    function pnOrderState()
    {
        //跑客端接口权限校验
        pnerificationToken();
        $order = M('order');
        $where['dispatch_id'] = array('eq', I('uid'));
        $where['status'] = array('between', '2,6');
        $ret = $order->where($where)->field('status,pay_status,pay_method,send_address_floor,reci_address_floor,reci_address,send_address,order_time,is_reservation,reservation_time,real_amount,dispatch_get_money,order_id,order_type,queue_address')->select();
        if ($ret) {
            return RET(200, '获取成功', $ret);
        } else {
            return RET_NO_V(401, '无未完成订单');
        }
    }

    /**
     * @api {get} pnOrderDetail/uid/:uid/token/:token/order_id/:order_id/ 【跑客端】订单详情--我的跑腿
     * @apiName 【跑客端】我的跑腿
     * @apiGroup PN
     *
     * @apiParam {Int} dispatch_id 跑客id.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiParam {int} order_id 订单id.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * {
     *    "retCode": 200,
     *    "retDesc": "获取成功",
     *    "retValue": {
     *           status:1        //0、未处理，1、待分配，2、已分配 3、已到达 4、已拍照 5、 已取件 6、已送达，7、已完成，9，已取消。
     *    }
     * }
     * @apiError retCode=401为返回无未完成订单.
     */
    function pnOrderDetail()
    {
        //跑客端接口权限校验
        //pnerificationToken();
        $order = M('order');
        $ret = $order->where(array('order_id' => I('order_id')))->find();

        if ($ret['send_address_floor']) {
            $ret['send_address_floor'] = '(' . $ret['send_address_floor'] . ')';
        }
        if ($ret['reci_address_floor']) {
            $ret['reci_address_floor'] = '(' . $ret['reci_address_floor'] . ')';
        }
        if ($ret) {
            return RET(200, '获取成功', $ret);
        } else {
            return RET_NO_V(401, '无未完成订单');
        }
    }

    /**
     * @api {get} pnFindOrder/uid/:uid/token/:token/ 【跑客端】打开订单的轮询
     * @apiName 【跑客端】打开订单的轮询
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客id.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiParam {String} pnLat 跑客纬度
     * @apiParam {String} pnLng 跑客纬度
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * {
     *    "retCode": 200,
     *    "retDesc": "获取成功",
     *    "retValue": {
     *
     *    }
     * }
     * @apiError retCode=400为返回无待接订单.
     */

    function pnFindOrder()
    {
        //跑客端接口权限校验
        pnerificationToken();
        $order = M('order');
        $ret = $order->where(array('status' => 0, 'is_valid' => 1))->field('order_id,send_address,reci_address,send_latit,send_longit,res_type,remark')->select();
        $length = count($ret);
        $start = I('pnLat') . "," . I('pnLng');
        $arr = array();
        if ($length > 0) {
            for ($i = 0; $i < $length; $i++) {
                $end = $ret[$i]['send_latit'] . "," . $ret[$i]['send_longit'];
                $rets = line($start, $end);
                $distance = $rets['result']['routes'][0]['distance'];
                if ($distance < 3000) {
                    $arr[] = $ret[$i];
                }
            }
            if (count($arr) == 0) {
                return RET(200, "获得订单", $arr);
            } else {
                return RET_NO_V(400, "无待接订单");
            }
        } else {
            return RET_NO_V(400, "无待接订单");
        }
    }

    /**
     * @api {get} pnOrderSet1/uid/:uid/token/:token/order_id/:order_id/ 【跑客端】取货已到达接口
     * @apiName 【跑客端】取货已到达接口
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客id.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiParam {String} order_id 订单id
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * {
     *    "retCode": 200,
     *    "retDesc": "已到达取货地点",
     *
     * }
     * @apiError retCode=400为到达时间修改失败.
     * @apiError retCode=401为未查到您有未完成订单.
     * @apiError retCode=402为重复提交错误.
     *
     */
    function pnOrderSet1()
    {
        //跑客端接口权限校验
        pnerificationToken();
        $order_id = I('order_id');
        $dispatch_id = I('uid');
        $order = M('order');
        $results = validationOrder(2, $order_id, $dispatch_id);
        if ($results) {
            $rets = $order->where(array('order_id' => $order_id))->field('get_time,reservation_time')->find();
            $date = date('Y-m-d H:i:s');
            $nowtime = strtotime($date);
            $reservation_time = strtotime($rets['reservation_time']);
            $time = $reservation_time - $nowtime;
            //判断是否在预约时间段
            if ($time > 600) {
                return RET_NO_V(400, "未到预约时间，请您在预约时间前十分钟之内完成！");
            }
            if ($rets['get_time']) {
                return RET_NO_V(402, "重复提交错误");
            } else {
                $ret = $order->where(array('order_id' => $order_id))->save(array('get_time' => $date, 'status' => 3));
                if ($ret) {
                    return RET_NO_V(200, "已到达取货地点");
                } else {
                    return RET_NO_V(400, "到达时间修改失败");
                }
            }
        } else {
            return RET_NO_V(401, "订单被取消或状态异常");
        }
    }

    /**
     * @api {get} pnOrderSet2/uid/:uid/token/:token/order_id/:order_id/imgPath/:imgPath 【跑客端】取货拍照接口
     * @apiName 【跑客端】取货拍照接口
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客id.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiParam {String} order_id 订单id
     * @apiParam {String} imgPath 图片路径
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * {
     *    "retCode": 200,
     *    "retDesc": "储存照片成功",
     *
     * }
     * @apiError retCode=400为储存上传照片路径失败.
     * @apiError retCode=401为未查到您有未完成订单.
     */
    function pnOrderSet2()
    {
        //跑客端接口权限校验
        pnerificationToken();
        $order_id = I('order_id');
        $order = M('order');
        $dispatch_id = I('uid');
        $status = $order->where(array('order_id' => $order_id))->field('status')->find();
        /*******发送短信********/
//                if($status[is_sms]){
//                    $message_obj = $order->where(array('order_id' => $order_id))->field('reci_mobile,mobile,d.dispatch_name')->join('db_dispatch as d on o.dispatch_id = d.dispatch_id')->find();
//                    $message_obj["dispatch_name"] = substr($message_obj["dispatch_name"],0,3)."师傅";
//
//                    if($message_obj && preg_match("/1[3458]{1}\d{9}$/", $message_obj['reci_mobile'])){
//                       send_order_sms($message_obj['reci_mobile'], $message_obj);
//                    }
//                }
       /***********************/
        if ($status['status'] == 2) {
      
            return RET_NO_V(401, "您还未到达，不能拍照！");
        }

    
        $results = validationOrder(3, $order_id, $dispatch_id);
        if ($results) {
            $ret = $order->where(array('order_id' => $order_id))->save(array('disp_before_img' => I('imgPath'), 'status' => 4));
            if ($ret) {
                return RET_NO_V(200, '储存照片成功');
            } else {
                return RET_NO_V(400, "储存上传照片路径失败");
            }
        } else {
            return RET_NO_V(401, "未查到您有未完成订单");
        }
    }

    /**
     * @api {get} pnOrderSet3/uid/:uid/token/:token/order_id/:order_id/imgPath/:imgPath 【跑客端】已取件接口
     * @apiName 【跑客端】已取件接口
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客id.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiParam {String} order_id 订单id
     * @apiSuccessExample 成功返回:
     *  HTTP/1.1 200 OK
     * {
     *    "retCode": 200,
     *    "retDesc": "状态修改成功",
     * }
     * @apiError retCode=400为状态修改失败.
     * @apiError retCode=401为未查到您有未完成订单.
     */
    function pnOrderSet3()
    {
        //跑客端接口权限校验
        pnerificationToken();
        $time = date('Y-m-d H:i:s');
        $order_id = I('order_id');
        $order = M('order o');
        $dispatch_id = I('uid');
        $results = validationOrder(4, $order_id, $dispatch_id);
        /*******发送短信********/
        $status = $order->where(array('order_id' => $order_id))->field('is_sms')->find();
      
                if($status[is_sms]){
                    $message_obj = $order->where(array('order_id' => $order_id))->field('reci_mobile,mobile,d.dispatch_name')->join('db_dispatch as d on o.dispatch_id = d.dispatch_id')->find();
                    $message_obj["dispatch_name"] = substr($message_obj["dispatch_name"],0,3)."师傅";

                    if($message_obj && preg_match("/1[3458]{1}\d{9}$/", $message_obj['reci_mobile'])){
                       send_order_sms($message_obj['reci_mobile'], $message_obj);
                    }
                }
       /***********************/
        if ($results) {
            $ret = $order->where(array('order_id' => $order_id))->save(array('status' => 5, 'get_goods_time' => $time));
            $remark = '订单已取件';
            $context = '订单（' . $results['order_number'] . '）已取件';
            if ($results['order_type'] == 3) {
                $remark = '已排队';
                $context = '订单（' . $results['order_number'] . '）已排队';
            } elseif ($results['order_type'] == 2) {
                $remark = '已代买';
                $context = '订单（' . $results['order_number'] . '）已代买';
            }

            $user_msg_ret = create_user_message($results['user_id'], $remark, $context, $context . '，即刻为您完成');
            if ($ret && $user_msg_ret) {
                RET(200, '状态修改成功', $time);
            } else {
                RET_NO_V(400, "状态修改失败");
            }
        } else {
            return RET_NO_V(401, "未查到您有未完成订单");
        }
    }

    /**
     * @api {get} pnOrderSet4/uid/:uid/token/:token/order_id/:order_id/ 【跑客端】已送达接口
     * @apiName 【跑客端】已送达接口
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客id.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiParam {String} order_id 订单id
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * {
     *    "retCode": 200,
     *    "retDesc": "状态修改成功"
     * }
     * @apiError retCode=400为状态修改失败.
     * @apiError retCode=401为未查到您有未完成订单.
     * @apiError retCode=400为短信验证码发送失败.
     */
    function pnOrderSet4()
    {
        //跑客端接口权限校验
        pnerificationToken();
        $order_id = I('order_id');
        $order = M('order');
        $dispatch_id = I('uid');
        $results = validationOrder(5, $order_id, $dispatch_id);
        if ($results) {
            $order->startTrans();
            $ret = $order->where(array('order_id' => $order_id))->save(array('status' => 6, 'disp_arrive_time' => date('Y-m-d H:i:s', time())));
            if ($ret) {
                $retsss = $order->where(array('order_id' => $order_id))->field('order_type,reci_mobile,replace_mobile,send_mobile')->find();
                $userTel = $retsss['reci_mobile'];

                $remark = '订单已送达';
                $context = '订单（' . $results['order_number'] . '）已送达';
                if ($retsss['order_type'] == 3) {
                    $userTel = $retsss['replace_mobile'];
                    $remark = '排队已到时间';
                    $context = '排队订单（' . $results['order_number'] . '）已到时间';
                }

                if ($retsss['order_type'] == 2) {
                    $userTel = $retsss['send_mobile'];
                }

                $user_msg_ret = create_user_message($results['user_id'], $remark, $context, $context . '，即将完成');
                $retss = $this->sendMSMConsignee($userTel, $order_id);
                if ($retss && $user_msg_ret) {
                    $order->commit();
                    return RET_NO_V(200, "状态修改成功");
                } else {
                    $order->rollback();
                    return RET_NO_V(400, "短信验证码发送失败");
                }
            } else {
                $order->rollback();
                RET_NO_V(400, "状态修改失败");
            }
        } else {
            return RET_NO_V(401, "未查到您有未完成订单");
        }
    }

    /**
     * @api {get} pnOrderSet5/uid/:uid/token/:token/order_id/：order_id/getcode/:getcode/order_id/:order_id 【跑客端】已完成接口
     * @apiName 【跑客端】已完成接口
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客id.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiParam {String} order_id 订单id
     * @apiParam {String} getcode 验证码
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * {
     *    "retCode": 200,
     *    "retDesc": "状态修改成功",
     *
     * }
     * @apiError retCode=400为状态修改失败.
     * @apiError retCode=401为未查到您有未完成订单.
     * @apiError retCode=402为验证码验证失败.
     *
     */
    function pnOrderSet5()
    {
        //跑客端接口权限校验
        pnerificationToken();
        $order_id = I('order_id');
        $order = M('order');
        $results = validationOrder(6, $order_id, I('uid'));

        if ($results) {
            $rets = $order->where(array('order_id' => $order_id))->field('dispatch_id,get_vali_code,total_mileage,user_id,order_amount,goods_amount,is_have_price,is_reservation,order_type,real_amount,pay_method,is_sms')->find();
            $order->startTrans();
            if ($rets['get_vali_code'] == I('getcode')) {
//                dump('验证码正确');
//                dump('订单的类别：');
//                dump($rets['order_type']);
//                dump('是否知道价格：'.$rets['is_have_price']);
                $dispatch_upret = 1;
                $aumont = $rets['order_amount'];
                if (2 == $rets['order_type'] && $rets['is_have_price'] == 1) {
                    $aumont = $rets['order_amount'] - $rets['goods_amount'];
                }
//                dump('分成金额：');
//                dump($aumont);

                //跑客每日首单奖励2元
//                dispatch_insurance($rets['dispatch_id'],$order_id,10);

                $ret = $order->where(array('order_id' => $order_id))->save(array('status' => 7, 'finish_time' => date('Y-m-d H:i:s', time())));//订单状态修改

                $oa_ret = pnOrderAccount($order_id);//真实的跑腿收入--跑腿费扣除佣金的钱
//                dump('计算跑客收入结果:');
//                dump($oa_ret);
                $reco_ret = 1;
//                if($rets['pay_method'] != 3){// 余额支付的订单，不再参与分成
//                $reco_ret = recommend_order_reward($rets['user_id'], I('uid'), $order_id, $aumont);//营销分成
//                }
                $reco_ret = recommend_robpn_reward($rets['user_id'], I('uid'), $order_id, $aumont);//奖励跑客的推荐人订单金额的20%
//                dump('营销分成结果:');
//                dump($reco_ret);
//                $reco_act_ret = recommend_active_reward($rets['dispatch_id'], $order_id);//推荐奖励
//                dump('推荐奖励结果：');
//                dump($reco_act_ret);
                $user_lret = user_level(C('order_exp'), $rets['user_id']);//每笔订单用户奖励的经验值
//                dump('用户经验值处理结果:');
//                dump($user_lret);

                $pn_lret = pnLevel(C('order_pn_exp'), I('uid'));//每笔订单跑客奖励的经验值
//                dump('跑客经验值处理结果:');
//                dump($pn_lret);

                //订单完成，删除中间表数据
                $rems_db = M('order_resmsm');

                $del_resmsm_ret = $rems_db->where('order_id=' . $order_id)->delete();
//                dump('删除中间表处理结果:');
//                dump($rems_db->getLastSql());
//                dump($del_resmsm_ret);

                $recommented_reward = send_coupon( I('uid'));//新用户，第一单完成，随机奖励推荐人

                if (1 == $rets['order_type']) {
//                    dump('订单类别是取送订单，跑客总里程和订单总数加1');
                    //更新跑客总里程和订单总数加1
                    $dispatch_upret = M('dispatch')->execute("update db_dispatch set comp_order_num=comp_order_num+1,totalmileage=totalmileage+" . $rets['total_mileage'] . " where dispatch_id=" . I('uid'));
                }


                if (2 == $rets['order_type']) {
                    //dump('订单类别是代买订单，是否知道价格：');
                    //dump($rets['is_have_price']);
                    if ($rets['is_have_price'] == 1) {
                        //dump('知道价格，将价格发给跑客---跑客余额表：'.$rets['goods_amount']);
                        $pnod_ret = pnOrderDetail(I('uid'), $rets['goods_amount'], 2, '代买订单垫付商品金额' . $rets['goods_amount'] . '元', $order_id);//余额记录增加
                        //更新跑客总里程和订单总数加1,余额=余额+商品金额
                        $dispatch_upret = M('dispatch')->execute("update db_dispatch set comp_order_num=comp_order_num+1,totalmileage=totalmileage+" . $rets['total_mileage'] . ",cash_balance=cash_balance+" . $rets['goods_amount'] . " where dispatch_id=" . I('uid'));
//                        dump('修改跑客表的余额字段（垫付商品钱），完成订单总数+1，总里程+此单的总里程'.$rets['total_mileage']);
                    } else if ($rets['is_have_price'] == 2) {
//                        dump('不知道价格，修改跑客表的完成订单总数+1，总里程+此单的总里程'.$rets['total_mileage']);
                        //更新跑客总里程和订单总数加1
                        $dispatch_upret = M('dispatch')->execute("update db_dispatch set comp_order_num=comp_order_num+1,totalmileage=totalmileage+" . $rets['total_mileage'] . " where dispatch_id=" . I('uid'));

                    }
                }
                if (3 == $rets['order_type']) {
//                    dump('订单类别是代排队订单，订单总数加1');
                    //更新跑客订单总数加1
                    $dispatch_upret = M('dispatch')->execute("update db_dispatch set comp_order_num=comp_order_num+1 where dispatch_id=" . I('uid'));
                }

                //预约单赠送优惠券2元
                if ($rets['is_reservation'] == 1 && round($rets['total_mileage'],2) >= 2.50 ) {//bccomp ：left>$right 返回 1,相等返回0，float类型比较函数，出现float(12.4) ！= float(12.4)的情况，这个函数避免 了这种情况
                    $coupon_ret = newuser_reward_coupon($rets['user_id'], 'zW73kg5ZJ25#D%IW',$order_id);
                    if (1 == $coupon_ret) {
                        //优惠券发放成功发消息
                        $coupon_info = M("coupon_info");
                        $cou_ret = $coupon_info->field('coupon_value')->where("coupon_key='zW73kg5ZJ25#D%IW' and is_push=1 and surplus_num >0")->find();
                        $msg_ret = create_user_message($rets['user_id'], '预约单有礼', '下预约单【'.$results['order_number'].'】赠送' . $cou_ret['coupon_value'] . '元优惠券', '下预约单【'.$results['order_number'].'】赠送' . $cou_ret['coupon_value'] . '元优惠券');
                        if (!$msg_ret) {//调用方法，返回  0失败 roll，其他值不管
                            $order->rollback();
                            return RET_NO_V(400, "预约单优惠券赠送失败");
                        }
                    }
                }
                //==========订单积分奖励 start cln20161203==========
                $points_ret = 1;
                $points_msg_ret = 1;
//                if ($rets['pay_method'] != 3 && C('order_points') && floatval($rets['real_amount']) > 0.00) {//余额支付时，不送积分；支付宝、微信支付时，送积分
                if ( C('order_points') && floatval($rets['real_amount']) > 0.00) {
                    $points_value = round(C('order_points') * $rets['real_amount']);
                    if ($points_value > 0) {
                        $points_ret = addPoints(array('user_id' => $rets['user_id'], 'points_type' => 1, 'points_value' => $points_value, 'remark' => '订单积分奖励', 'from_id' => $order_id));
                        $points_msg_ret = create_user_message($rets['user_id'], '订单送积分成功', '订单' . $results['order_number'] . '已完成，奖励' . $points_value . '积分', '订单' . $results['order_number'] . '已完成，奖励' . $points_value . '积分');
                    }
                }
                //==========订单积分奖励 end==========
                //===========发送短信  start 2016-12-16.cln================
                if ($rets['is_sms']) {
                    $user_obj = M('app_users')->field('mobile')->where(array('user_id' => $rets['user_id']))->find();
                    if ($user_obj && preg_match("/1[3458]{1}\d{9}$/", $user_obj['mobile']))
                        send_order_finish_sms($user_obj['mobile'], $results['order_number']);
                }
                //============发送短信  end =======

                //============推广短信 start=======
                app_market_order_linkman($order_id);
                //===========推广短信 end============
                if ($ret && $oa_ret && $reco_ret && $user_lret && $pn_lret && $dispatch_upret && $del_resmsm_ret && $points_ret && $points_msg_ret&&$recommented_reward) {
//                    dump('订单修改成功，提交事务');
                    $order->commit();
                    return RET_NO_V(200, "状态修改成功");
                } else {
                    $order->rollback();
                    return RET_NO_V(400, "状态修改错误");
                }


            } else {
                $order->rollback();
                RET_NO_V(402, '验证码验证失败');
            }
        } else {
            return RET_NO_V(401, "未查到您有未完成订单");
        }
    }

    /**
     * @api {get} pnOrderSet5_V1/uid/:uid/token/:token/order_id/：order_id/getcode/:getcode/ 【跑客端】已完成接口
     * @apiName 【跑客端】短信验证码校验
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客id.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiParam {String} order_id 订单id
     * @apiParam {String} getcode 验证码
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * {
     *    "retCode": 200,
     *    "retDesc": "状态修改成功",
     *
     * }
     * @apiError retCode=400为状态修改失败.
     * @apiError retCode=401为未查到您有未完成订单.
     * @apiError retCode=402为验证码验证失败.
     *
     */
    function pnOrderSet5_V1()
    {
        //跑客端接口权限校验
        pnerificationToken();
        $order_id = I('order_id');
        $order = M('order');
        $results = validationOrder(6, $order_id, I('uid'));
        if ($results) {
            $rets = $order->where(array('order_id' => $order_id))->field('get_vali_code,user_id,order_amount')->find();
            if ($rets['get_vali_code'] == I('getcode')) {
                $ret = $order->where(array('order_id' => $order_id))->save(array('status' => 7, 'disp_arrive_time' => date('Y-m-d H:i:s', time())));
                if ($ret) {

                    //帮币金额处理
                    pnCoin(C('order_coin'), 1, I('uid'), "完成订单奖励" . C('order_coin') . '个帮币', "完成订单奖励");
                    //财务结算
                    pnOrderAccount($order_id);
                    //经验值
                    user_level(C('order_pn_exp'), I('uid'));
                    //营销分成
                    recommend_order_reward($rets['user_id'], I('uid'), $order_id, $rets['order_amount']);
                    //用户经验值处理?
                    user_level(C('order_exp'), $rets['user_id']);
                    //跑客经验值处理
                    pnLevel(C('order_pn_exp'), I('uid'));

                    return RET_NO_V(200, "状态修改成功");
                } else {
                    RET_NO_V(400, "状态修改失败");
                }
            } else {
                RET_NO_V(402, '验证码验证失败');
            }
        } else {
            return RET_NO_V(401, "未查到您有未完成订单");
        }
    }

    /**
     * @api {post} setPnOrdersModel/uid/:uid/token/:token/model/:model 【跑客端】设置接单单模式
     * @apiName 【跑客端】设置接单单模式
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客id.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiParam {Int} model 接单模式 1 校园模式 3 社会模式 5 超人模式
     *
     */
    public function setPnOrdersModel()
    {
        $dispatch = M("dispatch");
        $order_model = $dispatch->where(array('dispatch_id' => I('uid')))->field('order_model')->find();
        if ($order_model == I('model')) {
            RET_NO_V(201, "抱歉，当前模式和设置模式一样");
        } else {
            $ret = $dispatch->where(array('dispatch_id' => I('uid')))->save(array('order_model' => I('model')));
            if ($ret) {
                RET_NO_V(200, "恭喜，设置成功！");
            } else {
                RET_NO_V(400, "抱歉，设置失败，请重试！");
            }
        }
    }

    public function test()
    {
        //语音留言信息的处理test();
//        $savePath = '/order_amr/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';
//        $return = up_amr($savePath);
//        dump($return);
        //推送服务器测试
        //push_server_data();
    }

    /**
     * @api {get} pnOrderSet3ChangeImg/uid/:uid/token/:token/order_id/:order_id/disp_before_img/:disp_before_img 【跑客端】订单图片更换
     * @apiName 【跑客端】订单图片更换
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客id.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiParam {Int} order_id 订单id
     * @apiParam {String} disp_before_img 更换后的图片地址.
     *
     */
    function pnOrderSet3ChangeImg()
    {
        //鉴权
        pnerificationToken();
        //获取订单ID
        $order_id = I('order_id');
        $order = M('order');
        $ret = $order->where(array('order_id' => $order_id, 'status' => 4))->save(array('disp_before_img' => I('disp_before_img')));
        return RET(200, "图片更新成功！");

    }

    /**
     *语音留言信息的处理
     */
    public function ptVioceUpload()
    {
        $savePath = '/order_amr/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';
        $return = up_amr($savePath);

        return RET(200, '音频上传成功', $return);
    }

    /**
     * @api {get} uploadImg/uid/:uid/token/:token/uptype/:uptype 照片上传
     * @apiName 照片上传
     * @apiGroup common
     * @apiParam {Int} uid 用户id 选填.
     * @apiParam {Int} uid 跑客id 选填.
     * @apiParam {Int} order_id 传货物图片时填写 选填.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiParam {Int} uptype 上传类型 1.用户头像上传 2.跑客头像上传 3.取货图片上传.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * {
     *    "retCode": 200,
     *    "retDesc": "上传成功",
     *    "retValue": {
     *          Uploads/2016/08/01/20160801014432403767203.png 返回图片路径
     *    }
     * }
     * @apiError retCode=400为上传失败.
     * {
     *    "retCode": 400,
     *    "retDesc": "上传失败",
     *    "retValue": {
     *          错误信息提示
     *    }
     * }
     */
    public function uploadImg()
    {

        $uptype = I('uptype');
        switch ($uptype) {
            case 1:
                verificationToken();
                $savePath = '/userHeadImg/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';
                $return = upImg($savePath);
                //var_dump($return["retCode"]);
                if ($return["retCode"] == 400) {
                    return RET_NO_V(400, $return["retDesc"]);
                } else {
                    $app_users = M('app_users');
                    $ret = $app_users->where(array('user_id' => I('uid')))->save(array('avatar' => $return["retDesc"]));
                    if ($ret) {
                        RET(200, "头像储存成功", $return["retDesc"]);
                    } else {
                        RET_NO_V(401, "头像储存失败");
                    }
                }
                break;
            case 2:
                pnerificationToken();
                $savePath = '/pnHeadImg/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';
                $return = upImg($savePath);
                if ($return["retCode"] == 400) {
                    return RET_NO_V(400, $return["retDesc"]);
                } else {
                    $dispatch = M('dispatch');
                    $ret = $dispatch->where(array('dispatch_id' => I('uid')))->save(array('avatar' => $return["retDesc"]));
                    if ($ret) {
                        return RET(200, "头像储存成功", $return["retDesc"]);
                    } else {
                        return RET_NO_V(401, "头像储存失败");
                    }
                }
                break;
            case 3:
                pnerificationToken();
                $savePath = '/goodsImg/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';
                $return = upImg($savePath);
                if ($return["retCode"] == 400) {
                    return RET_NO_V(400, $return["retDesc"]);
                } else {
                    $order = M('order');
                    $ret = $order->where(array('order_id' => I('order_id')))->save(array('disp_before_img' => $return["retDesc"]));
                    if ($ret) {
                        return RET(200, "图片储存成功", $return["retDesc"]);
                    } else {
                        return RET_NO_V(401, "图片储存失败");
                    }
                }
                break;
        }
    }


    /**
     * @api {get} getHelp/uid/:uid/token/:token/cid/:cid  获取帮助
     * @apiName 获取帮助
     * @apiGroup uptype
     *
     * @apiParam {Int} uid 用户ID.
     * @apiParam {String} token token,每次登录都会更改.
     * @apiParam {Int} cid 分类ID 0 顶级分类
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *
     */

    function getHelp()
    {
        //不做校验
        $help_type = M("help_type");
        $type = I('type');//1：跑客2：用户

        $where = 'level = 0';
        if ($type == 1)
            $where .= " and help_name like '跑客端%'";
        else
            $where .= " and help_name like '用户端%'";

        $help_parent = $help_type->where($where)->find();
        if ($help_parent) {
            $count = $help_type->where('parent_id=' . $help_parent['help_type_id'])->count();
            $ret = $help_type->where('parent_id=' . $help_parent['help_type_id'])->order('sort desc')->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->select();
            $rets['data'] = $ret;
            $rets['count'] = ceil($count / I("pagenum"));
            if ($ret) {
                return RET(0, "获取帮助数据成功！", $rets);
            } else {
                return RET_NO_V(1, "获取帮助数据失败！");
            }
        } else {
            return RET_NO_V(1, "获取帮助数据失败！");
        }

    }

    /**
     * @api {get} getHelp/uid/:uid/token/:token/cid/:cid  获取帮助正文
     * @apiName 获取帮助正文
     * @apiGroup uptype
     *
     * @apiParam {Int} uid 用户ID.
     * @apiParam {String} token token,每次登录都会更改.
     * @apiParam {Int} cid 分类ID 0 顶级分类
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *
     */
    function getHelpDetails()
    {
        //不做校验
        $online_help = M("online_help");
        $ret = $online_help->where(array('help_type_id' => I("cid")))->find();
        $ret['help_content'] = htmlspecialchars_decode($ret['help_content']);
        if ($ret) {
            return RET(0, "获取帮助数据成功！", $ret);
        } else {
            return RET_NO_V(1, "获取帮助数据失败！");
        }
    }

    /**
     * @api {get} getConveyance/uid/:uid/token/:token/  获取交通工具
     * @apiName 获取交通工具
     * @apiGroup uptype
     *
     * @apiParam {Int} uid 用户ID.
     * @apiParam {String} token token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *
     */
    function getConveyance()
    {
        //接口权限校验
        pnerificationToken();
        $conveyance = M("conveyance");
        $ret = $conveyance->select();
        if ($ret) {
            return RET(0, "获取交通工具数据成功！", $ret);
        } else {
            return RET_NO_V(1, "获取交通工具数据失败！");
        }
    }

    /**
     * @api {get} getUserDiscount/uid/:uid/token/:token/  获取用户APP优惠信息
     * @apiName 获取用户APP优惠信息
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户ID.
     * @apiParam {String} token token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *
     */
    function getUserDiscount()
    {
        //接口权限校验
        verificationToken();
        $user_discount = M('user_discount');
        $count = $user_discount->count();
        $ret = $user_discount->field('title,intro,addtime,id')->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->select();
        $rets['data'] = $ret;
        $rets['count'] = ceil($count / I("pagenum"));
        if ($ret) {
            return RET(0, "获取数据成功！", $rets);
        } else {
            return RET_NO_V(1, "获取数据失败！");
        }
    }

    /**
     * @api {get} getUserDiscountContent/uid/:uid/token/:token/id/:id  获取用户APP优惠信息正文
     * @apiName 获取用户APP优惠信息正文
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户ID.
     * @apiParam {String} token token,每次登录都会更改.
     * @apiParam {String} id 消息ID.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *
     */
    function getUserDiscountContent()
    {
        //接口权限校验
        verificationToken();
        $user_discount = M('user_discount');
        $ret = $user_discount->where(array('id' => I('id')))->find();
        $ret['content'] = htmlspecialchars_decode($ret['content']);
        if ($ret) {
            return RET(0, "获取数据成功！", $ret);
        } else {
            return RET_NO_V(1, "获取数据失败！");
        }
    }


    /**
     * @api {get} changeUserConveyance/uid/:uid/token/:token/conveyance_id/:conveyance_id  更改用户交通工具
     * @apiName 更改用户交通工具
     * @apiGroup uptype
     *
     * @apiParam {Int} uid 用户ID. conveyance_id
     * @apiParam {String} token token,每次登录都会更改.
     * @apiParam {Int} conveyance_id 交通工具
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *
     */

    function changeUserConveyance()
    {
        //接口权限校验
        pnerificationToken();
        $dispatch = M("dispatch");
        if (I("conveyance_id")) {
            $ret = $dispatch->where(array('dispatch_id' => I('uid')))->save(array('conveyance_id' => I("conveyance_id")));
            if ($ret) {
                return RET_NO_V(0, "更改交通工具数据成功！");
            } else {
                return RET_NO_V(1, "更改交通工具数据失败！");
            }
        } else {
            return RET_NO_V(2, "用户交通工具ID未填写！");
        }

    }

    /**
     * @api {get} changePnUserinfo/uid/:uid/token/:token/  注册跑客信息进入审核
     * @apiName 注册跑客信息进入审核
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户ID. conveyance_id
     * @apiParam {String} token token,每次登录都会更改.
     * @apiParam {String} dispatch_name 真实姓名
     * @apiParam {String} cert_number 身份证号
     * @apiParam {String} cert_face 身份证正面
     * @apiParam {String} cert_wrong 身份证反面
     * @apiParam {String} cert_hand 手持身份证照片
     * @apiParam {String} conveyance_id 交通工具ID
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *
     */

    function changePnUserinfo()
    {
        pnerificationToken();
        $dispatch = M("dispatch");
//        $dispatch_obj = $dispatch->field('dispatch_id')->where(array('cert_number'=>I("cert_number")))->select();
//        if($dispatch_obj){
//            return RET_NO_V(1, "身份证号不能重复，请重新输入！");
//        }

        $data = array(
            "is_audit" => 1,  //是否审核通过(0 未提交审核 1已提交审核，2已经审核通过 3审核未通过)
            "dispatch_name" => urldecode(I("dispatch_name")),   //解码一下
            "cert_number" => I("cert_number"),
            "cert_face" => I("cert_face"),
            "cert_wrong" => I("cert_wrong"),
            "cert_hand" => I("cert_hand"),
            "conveyance_id" => I("conveyance_id"),
            "mater_submit_time" => date('Y-m-d H:i:s', time())//提交资料的时间
        );
        $ret = $dispatch->where(array('dispatch_id' => I('uid')))->save($data);

        if ($ret) {
            return RET_NO_V(0, "提交注册成功！");
        } else {
            return RET_NO_V(1, "提交注册失败！");
        }
    }


    /**
     * @api {get} changePnUserinfoPic/uid/:uid/token/:token/  注册跑客信息图片资料上传
     * @apiName 注册跑客信息图片资料上传
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户ID. conveyance_id
     * @apiParam {String} token token,每次登录都会更改.
     * @apiParam {Int} type 1 身份证正面 2 身份证反面 3 手持身份证照片
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *
     */

    function changePnUserinfoPic()
    {
        pnerificationToken();
        $type = I('type');
        switch ($type) {
            case 1:
                $savePath = '/userinfodata/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';
                $return = upImg($savePath);
                //var_dump($return["retCode"]);
                if ($return["retCode"] == 400) {
                    return RET_NO_V(400, $return["retDesc"]);
                } else {
                    $dispatch = M('dispatch');
                    $ret = $dispatch->where(array('dispatch_id' => I('uid')))->save(array('cert_face' => $return["retDesc"]));
                    if ($ret) {
                        RET(200, "身份证正面储存成功", $return["retDesc"]);
                    } else {
                        RET_NO_V(401, "身份证正面储存失败");
                    }
                }
                break;
            case 2:
                $savePath = '/userinfodata/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';
                $return = upImg($savePath);
                //var_dump($return["retCode"]);
                if ($return["retCode"] == 400) {
                    return RET_NO_V(400, $return["retDesc"]);
                } else {
                    $dispatch = M('dispatch');
                    $ret = $dispatch->where(array('dispatch_id' => I('uid')))->save(array('cert_wrong' => $return["retDesc"]));
                    if ($ret) {
                        RET(200, "身份证反面储存成功", $return["retDesc"]);
                    } else {
                        RET_NO_V(401, "身份证反面储存失败");
                    }
                }
                break;
            case 3:
                $savePath = '/userinfodata/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';
                $return = upImg($savePath);
                //var_dump($return["retCode"]);
                if ($return["retCode"] == 400) {
                    return RET_NO_V(400, $return["retDesc"]);
                } else {
                    $dispatch = M('dispatch');
                    $ret = $dispatch->where(array('dispatch_id' => I('uid')))->save(array('cert_hand' => $return["retDesc"]));
                    if ($ret) {
                        RET(200, "手持身份证照片储存成功", $return["retDesc"]);
                    } else {
                        RET_NO_V(401, "	手持身份证照片储存失败");
                    }
                }
                break;
        }

    }

    /**
     * @api {get} setPnPosition/token/:token/uid/:uid/latitude/:latitude/longitude/:longitude 跑客位置更新
     * @apiGroup PN
     * @apiName 跑客位置更新(10秒更新一次)
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {string} latitude 纬度.
     * @apiParam {string} longitude 经度.
     **/
    function setPnPosition()
    {
        //校验token
        pnerificationToken();
        $dispatch = M("dispatch");
        //查询用户@place_up_time最后的更新位置，@todaytime今日在线时长，@onlinetime在线时间
        $rets = $dispatch->where(array('dispatch_id' => I('uid')))->field('place_up_time,todaytime,onlinetime,work_status')->find();
        //如果查询到用户端的以上信息
        if ($rets) {
            //判断是位置信息是否是今天的时间
            if (substr($rets['place_up_time'], 0, 10) == date('Y-m-d')) {
                //如果是听单中
                if ($rets['work_status'] == 1) {
                    //计算早上9点到下午8点的算法
                    if (strtotime(date('Y-m-d H:i:s')) >= strtotime(date('Y-m-d 08:00:00')) && strtotime(date('Y-m-d H:i:s')) <= strtotime(date('Y-m-d 20:00:00'))) {
                        if ((time() - strtotime($rets['place_up_time'])) >= 57) {
                            //如果是则更新今日在线时长+1
                            $rets['todaytime'] += 1;
                            //总在线时长加一
                            $rets['onlinetime'] += 1;
                        }

                    }
                }
            } else {
                //如果不是则今日在线时长清空
                $rets['todaytime'] = 1;
            }
            //存储今日在线时长
            $todaytime = $rets['todaytime'];
            //存储总在线时长
            $onlinetime = $rets['onlinetime'];
            //更新位置信息
            $ret = $dispatch->where(array('dispatch_id' => I('uid')))->save(array('todaytime' => $todaytime, 'onlinetime' => $onlinetime, 'latitude' => I("latitude"), 'longitude' => I("longitude"), 'place_up_time' => date('Y-m-d H:i:s')));
            //更新位置信息到跑客活跃表
            $active_db = M('dispatch_active');
            $active_ret = 1;
            //查找是否人位置信息已经存在
            $active_obj = $active_db->where(array('dispatch_id' => I('uid')))->find();
            //如果位置信息已经存在
            if ($active_obj) {
                //更新位置信息
                $active_ret = $active_db->where(array('dispatch_id' => I('uid')))->save(array('latitude' => I("latitude"), 'longitude' => I("longitude"), 'place_up_time' => date('Y-m-d H:i:s')));
            }
            //查询订单表获取附近的订单信息=========重要算法========
            //$order_resmsm = M("order_resmsm");
            //查询所有没有完成的订单
            //$order_datas = $order_resmsm->where(array('status'=>1))->field('order_lat,order_lng,order_data')->select();
            //dump($order_datas);
            //$order_data = array();
            //foreach($order_datas as $value ){
            //   $distance = getDistance($value['order_lat'],$value['order_lng'],I("latitude"),I("longitude"));
            //dump($distance);
            //    if($distance<=3){
            //        $order_data[]=json_decode($value['order_data']);
            //    }
            //}
            if ($ret && $active_ret) {
                return RET_NO_V(200, "定位成功！");
            } else {
                return RET_NO_V(201, "无订单数据");
            }
        }

    }

    /**
     * @api {get} setPnRegistrationID/token/:token/uid/:uid/registrationID/:registrationID 设置跑客推送ID
     * @apiName 设置跑客推送ID
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} registrationID 推送ID
     **/
    function setPnRegistrationID()
    {
        //校验token
        pnerificationToken();
        $dispatch = M("dispatch");
        $ret = $dispatch->where(array('dispatch_id' => I('uid')))->save(array('jpush_id' => I("registrationID")));
        if ($ret) {
            return RET_NO_V(0, "推送绑定成功！");
        } else {
            return RET_NO_V(1, "推送绑定失败！");
        }
    }

    /**
     * @api {get} setPnWorkStatus/token/:token/uid/:uid/workstatus/:workstatus 更改跑客工作状态
     * @apiName 更改跑客工作状态
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} workstatus 0 收工 1 听单中
     **/
    function setPnWorkStatus()
    {
        //校验token
        pnerificationToken();
        $dispatch = M("dispatch");

        //清空了跑客的经纬度位置
        //时间 2016年11月09日10:19:06
        $ret = $dispatch->where(array('dispatch_id' => I('uid')))->save(array('work_status' => I("workstatus"), 'latitude' => '', 'longitude' => ''));

        if ($ret) {
            return RET_NO_V(0, "更改跑客工作状态成功！");
        } else {
            return RET_NO_V(1, "更改跑客工作状态失败！");
        }


    }

    /**
     * @api {get} setPnOrderModel/token/:token/uid/:uid/model/:model 更改跑客为指派单模式
     * @apiName 更改跑客为指派单模式
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} model 1 开启 0 关闭
     **/
    function setPnOrderModel()
    {
        //校验token
        pnerificationToken();
        $dispatch = M("dispatch");
        $ret = $dispatch->where(array('dispatch_id' => I('uid')))->save(array('is_accept_dispatch' => I("model")));
        if ($ret) {
            return RET_NO_V(0, "更改跑客为指派单模式成功！");
        } else {
            return RET_NO_V(1, "更改跑客为指派单模式失败！");
        }

    }


    /**
     * @api {get} getReviewedStatus/uid/:uid/token/:token/  获取跑客审核状态审核状态
     * @apiName 获取跑客审核状态审核状态
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户ID
     * @apiParam {String} token token,每次登录都会更改.
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *
     */

    function getReviewedStatus()
    {
        pnerificationToken();
        $dispatch = M("dispatch");
        $ret = $dispatch->where(array('dispatch_id' => I('uid')))->field("is_audit")->find();
        $ret['audit_deac'] = is_audit_status($ret['is_audit']);
        if ($ret) {
            RET(0, "获取跑客审核状态审核状态成功！", $ret);
        } else {
            RET_NO_V(1, "获取跑客审核状态审核状态失败！");
        }
    }

    /**
     * @api {get} getPnUserInfo/uid/:uid/token/:token/  获取跑客信息
     * @apiName 获取跑客信息
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户ID
     * @apiParam {String} token token,每次登录都会更改.
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *
     */

    function getPnUserInfo()
    {
        pnerificationToken();
        $dispatch = M("dispatch");
        $conveyance = M("conveyance");
        $ret = $dispatch->where(array('dispatch_id' => I('uid')))->find();
        $dispatch_level = M("dispatch_level");
        $ret['leval'] = $dispatch_level->where(array('dispatch_level_id' => $ret['dispatch_level_id']))->field('level_name,level_img')->find();
        $ret['conveyance'] = $conveyance->where(array('conveyance_id' => $ret['conveyance_id']))->field('conv_name')->find();
        if ($ret) {
            RET(0, "获取跑客信息成功！", $ret);
        } else {
            RET_NO_V(1, "获取跑客信息失败！");
        }
    }

    /**
     * @api {get} getPnWallet/uid/:uid/token/:token/  获取跑客钱包信息
     * @apiName 获取跑客钱包信息(需要优化)
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户ID
     * @apiParam {String} token token,每次登录都会更改.
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *
     */

    function getPnWallet()
    {
        //鉴权
        pnerificationToken();
        $dispatch_balance = M("dispatch_balance");
        $ret = $dispatch_balance->where(array('dispatch_id' => I("uid")))->select();
        if ($ret) {
            RET(0, "获取跑客钱包信息成功！", $ret);
        } else {
            RET_NO_V(1, "获取跑客钱包信息为空！");
        }
    }


    /**
     * @api {get} getPnMyRecommend/uid/:uid/token/:token/  获取跑客我的推荐
     * @apiName 获取跑客我的推荐
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户ID
     * @apiParam {String} token token,每次登录都会更改.
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *
     */
    function getPnMyRecommend()
    {
        //鉴权
        pnerificationToken();
        $recommend = M("recommend");
        $ret = $recommend->where(array('recom_person_id' => I('uid')))->select();
        if ($ret) {
            RET(0, "获取跑客我的推荐成功！", $ret);
        } else {
            RET_NO_V(1, "获取跑客我的推荐为空！");
        }

    }

    /**
     * @api {get} getPnCoinDetail/uid/:uid/token/:token/page/:page/pagenum/:pagenum  获取跑客帮币记录
     * @apiName 获取跑客帮币记录
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户ID
     * @apiParam {String} token token,每次登录都会更改.
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *
     */
    function getPnCoinDetail()
    {
        //鉴权
        pnerificationToken();
        $coin_detail = M("coin_detail");
        $retss = M('dispatch')->where(array('dispatch_id' => I('uid')))->field('coin_balance')->find();
        if ($retss) {
            $count = $coin_detail->where(array('dispatch_id' => I('uid')))->count();
            $ret = $coin_detail->where(array('dispatch_id' => I('uid')))->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->order('coin_id desc')->select();
            $rets['data'] = $ret;
            $rets['count'] = ceil($count / I("pagenum"));
            $rets['coin_balance'] = $retss['coin_balance'];
            if ($ret) {
                return RET(0, "获取跑客帮币记录成功！", $rets);
            } else {
                return RET(1, "获取跑客帮币记录为空！", $rets);
            }
        } else {
            return RET_NO_V(400, "未获取跑客！");
        }


    }


    /**
     * @api {get} getPnDispatch_exp/uid/:uid/token/:token/page/:page/pagenum/:pagenum  获取跑客经验值记录
     * @apiName 获取跑客经验值记录
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户ID
     * @apiParam {String} token token,每次登录都会更改.
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *
     */

    function getPnDispatch_exp()
    {
        //鉴权
        pnerificationToken();
        $dispatch_exp = M("dispatch_exp");
        $retss = M('dispatch')->where(array('dispatch_id' => I('uid')))->field('growth_value')->find();
        if ($retss) {
            $count = $dispatch_exp->where(array('dispatch_id' => I('uid')))->count();
            $ret = $dispatch_exp->where(array('dispatch_id' => I('uid')))->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->order('id desc')->select();
            $rets['data'] = $ret;
            $rets['count'] = ceil($count / I("pagenum"));
            $rets['growth_value'] = $retss['growth_value'];
            if ($ret) {
                RET(0, "获取跑客经验值记录成功！", $rets);
            } else {
                RET(1, "获取跑客经验值记录为空！", $rets);
            }
        } else {
            RET_NO_V(400, "未获取跑客！");
        }

    }

    /**
     * @api {get} getPnMassage/token/:token/uid/:uid 跑客消息中心
     * @apiName 跑客消息中心（待优化）
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token token.
     **/

    function getPnMassage()
    {
        //鉴权
        pnerificationToken();
        $ret_data = upmsg_sys_list(I('uid'), 2, I("page"), I("pagenum"));
        //实例化消息表
        //$message = M('message');
        //查询属于跑客自已的通知消息
        //$count = $message->where(array('message_type' => 2))->count();
        //$ret = $message->where(array('message_type' => 2))->order('send_time desc')->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->select();
        //$rets['data'] = $ret;
        //$rets['count'] = ceil($count / I("pagenum"));
        if ($ret_data) {
            return RET(0, "获取消息成功！", $ret_data);
        } else {
            return RET_NO_V(1, "获取消息失败！");
        }
    }

    /**
     * @api {get} getPnNoticeNMessage/token/:token/uid/:uid 跑客通知消息（通知审核，处罚等消息）
     * @apiName 跑客通知消息
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {Int} message_id 消息ID.
     **/
    function getPnNoticeNMessage()
    {
        //实例化跑客信息表
        $disptch_message = M('disptch_message');
        //查询跑客的信息行数
        $count = $disptch_message->where(array('disptch_id' => I('uid')))->count();
        //查询跑客的信息
        $ret = $disptch_message->where(array('disptch_id' => I('uid')))->order('time desc')->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->select();
        //组装数据
        $rets['data'] = $ret;
        //行数计算
        $rets['count'] = ceil($count / I("pagenum"));
        if ($ret) {
            RET(0, "获取跑客通知消息成功！", $rets);
        } else {
            RET_NO_V(1, "获取跑客通知消息失败！");
        }
    }

    /**
     * @api {get} getPnNoticeNMessageShow/token/:token/uid/:uid/dispatch_msg_id/:dispatch_msg_id 跑客个人消息正文
     * @apiName 跑客个人消息正文
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {Int} message_id 消息ID.  dispatch_msg_id
     * @apiParam {Int} dispatch_msg_id 跑客消息id.
     **/
    function getPnNoticeNMessageShow()
    {
        //实例化跑客信息表
        $disptch_message = M('disptch_message');
        //查询跑客的信息数据
        $data = $disptch_message->where(array('dispatch_msg_id' => I('dispatch_msg_id')))->find();
        $disptch_message->where(array('dispatch_msg_id' => I('dispatch_msg_id')))->save(array('is_read' => 1));
        if ($data) {
            RET(0, "获取跑客通知消息正文成功！", $data);
        } else {
            RET_NO_V(1, "获取跑客通知正文消息失败！");
        }
    }

    /**
     * @api {get} getPnRecommend/token/:token/uid/:uid 跑客推荐数据
     * @apiName 跑客推荐数据
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {Int} message_id 消息ID.
     **/
    function getPnRecommend()
    {
        //实例化推荐关系表
        $recommend = M('recommend');
        //推荐的人数
        $count = $recommend->where(array('recom_person_id' => I('uid')))->count();
        //查询跑客的信息
        $ret = $recommend->where(array('recom_person_id' => I('uid')))->order('recommended_time desc')->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->select();
        //组装数据
        $rets['data'] = $ret;
        //行数计算
        $rets['count'] = ceil($count / I("pagenum"));
        if ($ret) {
            RET(0, "获取跑客推荐数据成功！", $rets);
        } else {
            RET_NO_V(1, "获取跑客推荐数据为空！");
        }


    }


    /**
     * @api {get} getPnMassageContent/token/:token/uid/:uid/message_id/:message_id 跑客消息中心正文
     * @apiName 跑客用户消息中心正文（待优化）
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {Int} message_id 消息ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     **/

    function getPnMassageContent()
    {
        //鉴权
        pnerificationToken();
        //取消消息标注
        $ret_status = see_upmsg_sys(I('uid'), I('message_id'));
        if ($ret_status) {
            $message = M('message');
            $ret = $message->where(array('message_id' => I('message_id'), 'message_type' => 2))->find();
            $ret['content'] = htmlspecialchars_decode($ret['content']);
            if ($ret) {
                return RET(0, "获取消息成功！", $ret);
            } else {
                return RET_NO_V(1, "获取消息失败！");
            }
        }

    }

    /**
     * @api {get} pnWallet/token/:token/uid/:uid/ 跑客我的钱包
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *   "retCode": 200,
     *   "retDesc": "获取成功",
     *   "retValue": [
     *   {
     *   "cashBalance": 累计赚取余额
     *   "withdrawCash": 可提现金额,
     *   "dayCount": 今日赚取金额
     *   }
     *   ]
     *    }
     *
     * @apiError retCode=400为获取跑客信息失败.
     * @apiError retCode=401为今日无订单.
     **/
    function pnWallet()
    {
        //接口权限校验
        pnerificationToken();
        $dispatch_balance = M('dispatch_balance');
        $dispatch = M('dispatch');
        $date = date('Y-m-d') . '%';
        $map['dispatch_id'] = I('uid');
        $map['time'] = array('like', $date);
        $ret = $dispatch_balance->where($map)->field('balance_id,time,order_id,balance_amount,change_memo,balance_type')->select();
        $cash_balance = $dispatch->where(array('dispatch_id' => I('uid')))->field('cash_balance')->find();
        $dayCount = 0;
        if ($ret) {
            for ($i = 0; $i < count($ret); $i++) {
                if ($ret[$i]['balance_type'] == 1 || $ret[$i]['balance_type'] == 3 || $ret[$i]['balance_type'] == 5 || $ret[$i]['balance_type'] == 10) {
                    $dayCount += $ret[$i]['balance_amount'];
                }
            }
        }
        $retc = $dispatch_balance->where(array('dispatch_id' => I('uid')))->select();
        //1、跑腿订单收入，2代购垫付入账，3帮币兑换收入，4提现支出，5推荐用户奖励,6保险金额,7押金200元'
        $cashBalance = 0;
        for ($i = 0; $i < count($retc); $i++) {
            if ($retc[$i]['balance_type'] == 1 || $retc[$i]['balance_type'] == 3 || $retc[$i]['balance_type'] == 5 || $retc[$i]['balance_type'] == 10) {
                $cashBalance += $retc[$i]['balance_amount'];
            }

        }
        //$cashBalance 累计赚取   C('deposit') 押金  C('lowest_cash') 最低提现
        $withdrawCash = $cash_balance['cash_balance'] - C('deposit') - C('lowest_cash');
        if ($withdrawCash < 0) {
            $withdrawCash = 0.00;
        } else {
            $withdrawCash = ($withdrawCash + C('lowest_cash')) / 100;
            $withdrawCash = floor($withdrawCash) * 100;
        }
        $data = array(
            'cashBalance' => number_format($cashBalance, 2),//累计赚取余额
            'withdrawCash' => number_format($withdrawCash, 2),//可提现
            'dayCount' => number_format($dayCount, 2),//今日赚取
            'cash_balance' => number_format($cash_balance['cash_balance'], 2)//
        );
        return RET(200, "获取成功", $data);
    }

    /**
     * @api {get} pnWalletOrderDetail/token/:token/uid/:uid/page/:page/num/:num 跑客钱包订单详情懒加载
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {Int} token 跑客token.
     * @apiParam {Int} page 第几页.
     * @apiParam {Int} num 几条数据.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *      "retCode": 200,
     *       "retDesc": "获取成功",
     *     "retValue": {
     *     "pagenum": 1,
     *      "orderDetail": [
     *      {
     *     "change_memo": "订单奖励",
     *     "balance_amount": "21.00",
     *     "time": "2016-08-15 10:46:09"
     *     },
     *     {
     *    "change_memo": "订单收入",
     *    "balance_amount": "27.00",
     *    "time": "2016-08-15 10:46:59"
     *    },
     * @apiError retCode=400为获取失败.
     * }
     **/

    function pnWalletOrderDetail()
    {
        pnerificationToken();
        $dispatch_balance = M("dispatch_balance");
        $count = $dispatch_balance->where(array('dispatch_id' => I('uid')))->count();
        $ret = $dispatch_balance->where(array('dispatch_id' => I('uid')))->order('time desc')->page(I('page'), I('num'))->field('balance_id,change_memo,balance_amount,time,balance_type')->select();
        if ($ret) {
            if ((int)$count % (int)I('num') == 0) {
                $pagenum = $count / (int)I('num');
                $pagenum = (int)$pagenum;
            } else {
                $pagenum = $count / (int)I('num') + 1;
                $pagenum = (int)$pagenum;
            }
            $data = array(
                'pagenum' => $pagenum,
                'orderDetail' => $ret
            );
            return RET(200, "获取成功", $data);
        } else {
            return RET_NO_V(400, "获取失败");
        }
    }

    /**
     * @api {get} pnApplyWithdrawal/token/:token/uid/:uid/ 跑客申请提款
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {Int} token 跑客token.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *      "retCode": 0,
     *       "retDesc": "已绑定",
     *     "retValue": {
     *          $withdrawCash 可提现余额
     *    },
     *  *     "retCode": 1,
     *       "retDesc": "未绑定",
     *     "retValue": {
     *   $withdrawCash 可提现余额
     *    },
     * }
     **/
    function pnApplyWithdrawal()
    {
        pnerificationToken();
        $dispatch = M("dispatch");
        $ret = $dispatch->where(array('dispatch_id' => I('uid')))->field('cash_balance')->find();
        //$cashBalance 累计赚取   C('deposit') 押金  C('lowest_cash') 最低提现
        $withdrawCash = $ret['cash_balance'] - C('deposit') - C('lowest_cash');
        if ($withdrawCash < 0) {
            $withdrawCash = 0.00;
        } else {
            $withdrawCash = ($withdrawCash + C('lowest_cash')) / 100;
            $withdrawCash = floor($withdrawCash) * 100;
        }
        $withdrawCash = number_format($withdrawCash, 2);
        $ret = $dispatch->where(array('dispatch_id' => I('uid')))->field('weinxin_openid')->find();
        if ($ret['weinxin_openid']) {
            return RET(0, "已绑定", $withdrawCash);
        } else {
            return RET(1, "未绑定", $withdrawCash);
        }
    }

    /**
     * @api {get} pnApplyWithdrawalLog/token/:token/uid/:uid/page/:page/num/:num 跑客申请提款
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {Int} token 跑客token.
     * @apiParam {Int} page 第几页
     * @apiParam {Int} num 一个页多少数据
     * @apiParam {String} token 用户token,每次登录都会更改.
     **/
    function pnApplyWithdrawalLog()
    {
        $dispatch_cash = M('dispatch_cash');
        $count = $dispatch_cash->where(array('dispatch_id' => I('uid')))->count();
        $ret = $dispatch_cash->where(array('dispatch_id' => I('uid')))->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->order('cash_record_id desc')->select();
        $rets['data'] = $ret;
        $rets['count'] = ceil($count / I("pagenum"));
        if ($ret) {
            return RET(200, "获取成功！", $rets);
        } else {
            return RET_NO_V(400, "获取失败");
        }
    }

    /**
     * @api {get} pnApplyWithdrawalSet/token/:token/uid/:uid/cash_account_type/:cash_account_type/cash_account_name/:cash_account_name/cash_account/:cash_account 跑客申请提款
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {String} cash_account_type 提现账号类型
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiParam {String} cash_account_name 提现账号名称
     * @apiParam {String} cash_account 提现账号
     *
     */
    function pnApplyWithdrawalSet()
    {
        pnerificationToken();
        $recommend_set = M('recommend_set');
        $data = array(
            'dispatch_id' => I('uid'),
            'cash_account_type' => I('cash_account_type'),
            'cash_account_name' => I('cash_account_name'),
            'cash_account' => I('cash_account')
        );
        $ret = $recommend_set->add($data);
        if ($ret) {
            return RET_NO_V(200, "保存成功");
        } else {
            return RET_NO_V(400, "保存失败");
        }
    }

    /**
     * @api {get} pnRecommend_set/token/:token/uid/:uid/type/:type/status/:status 跑客设置更改
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {String} type 更改类型 1 是否携带保温箱 2 保持屏幕常亮
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiParam {String} status 修改状态
     *
     */
    function pnRecommend_set()
    {
        pnerificationToken();
        $recommend_set = M('recommend_set');
        $type = I('type');
        if (1 == $type) {

            $ret = $recommend_set->where(array('dispatch_id' => I('uid')))->save(array('is_incubator' => I('status')));
            if ($ret) {
                RET(200, "修改成功", $ret);
            } else {
                RET_NO_V(400, "修改失败,请重试!");
            }
        } elseif (2 == $type) {
            $ret = $recommend_set->where(array('dispatch_id' => I('uid')))->save(array('hold_light' => I('status')));
            if ($ret) {
                RET(200, "修改成功", $ret);
            } else {
                RET_NO_V(400, "修改失败,请重试!");
            }
        }
    }

    /**
     * @api {get} dispatchBalanceDetail/token/:token/uid/:uid/balance_id/:balance_id/ 跑客账单详情
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {String} balance_id 账单id
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *      "retCode": 200,
     *       "retDesc": "返回成功",
     *     "retValue": {
     *
     *    },
     * "retCode": 400,
     *       "retDesc": "返回失败",
     *     "retValue": {
     *
     *    },
     */
    function dispatchBalanceDetail()
    {
        pnerificationToken();
        $ret = M('dispatch_balance')->where(array('balance_id' => I('balance_id')))->field('balance_type,balance_amount,time,remark')->find();
        if ($ret) {
            return RET(200, "返回成功", $ret);
        } else {
            return RET_NO_V(400, "返回失败");
        }
    }

    /**
     * @api {get} pnTaskHeadImg/token/:token/uid/:uid/task_id/:task_id/ 跑客上传照片任务
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {String} task_id 任务表id
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *      "retCode": 0,
     *       "retDesc": "未完成任务",
     *     "retValue": {
     *
     *    },
     * {
     *      "retCode": 1,
     *       "retDesc": "已完成任务",
     *     "retValue": {
     *
     *    },
     * "retCode": 400,
     *       "retDesc": "未查询到此跑客",
     *     "retValue": {
     *
     *    },
     * "retCode": 401,
     *       "retDesc": "添加任务记录失败",
     *     "retValue": {
     *
     *    },
     * retCode": 402,
     *       "retDesc": "添加任务记录失败",
     *     "retValue": {
     *
     *    },
     * retCode": 400,
     *       "retDesc": "增加帮币失败",
     *     "retValue": {
     *
     *    },
     * retCode": 404,
     *       "retDesc": "增加经验值失败",
     *     "retValue": {
     *
     *    },
     */
    function pnTaskHeadImg()
    {
        pnerificationToken();
        $dispatch = M("dispatch");
        $data = array(
            'dispatch_id' => I('uid'),
            'task_id' => I('task_id'),
            'remark' => '头像上传任务完成奖励2经验值和2帮币'
        );
        $dispatch_task = M('dispatch_task');
        $ret = $dispatch->where(array('dispatch_id' => I('uid')))->field('avatar')->find();
        if ($ret) {
            if ('Uploads/public/icon.png' == $ret['avatar']) {
                $data['is_complete'] = 'N';
                $retss = $dispatch_task->add($data);
                if ($retss) {
                    return RET_NO_V(0, "未完成任务");
                } else {
                    return RET_NO_V(401, "添加任务记录失败");
                }
            } else {
                $rets = pnCreditScore(I('uid'), 2, 1, '完成头像上传任务', '完成头像上传任务奖励2经验值');
                if ($rets) {
                    $result = pnCoin(2, 1, I('uid'), '完成头像上传任务', '完成头像上传任务奖励2帮币');
                    if ($result) {
                        $data['is_complete'] = 'Y';
                        $data['complete_time'] = date('Y-m-d H:i:s');
                        $retss = $dispatch_task->add($data);
                        if ($retss) {
                            return RET_NO_V(1, "已完成任务");
                        } else {
                            return RET_NO_V(402, "添加任务记录失败");
                        }
                    } else {
                        return RET_NO_V(400, "增加帮币失败");
                    }
                } else {
                    return RET_NO_V(404, "增加经验值失败");
                }
            }
        } else {
            return RET_NO_V(400, "未查询到此跑客");
        }
    }

    /**
     * @api {get} pnTaskOrder/token/:token/uid/:uid/task_id/:task_id/ 跑客第一笔订单任务
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {String} task_id 任务表id
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *      "retCode": 0,
     *       "retDesc": "未完成任务",
     *     "retValue": {
     *
     *    },
     * {
     *      "retCode": 1,
     *       "retDesc": "已完成任务",
     *     "retValue": {
     *
     *    },
     * "retCode": 400,
     *       "retDesc": "未查询到此跑客",
     *     "retValue": {
     *
     *    },
     * "retCode": 401,
     *       "retDesc": "添加任务记录失败",
     *     "retValue": {
     *
     *    },
     * retCode": 402,
     *       "retDesc": "添加任务记录失败",
     *     "retValue": {
     *
     *    },
     * retCode": 400,
     *       "retDesc": "增加帮币失败",
     *     "retValue": {
     *
     *    },
     * retCode": 404,
     *       "retDesc": "增加经验值失败",
     *     "retValue": {
     *
     *    },
     */
    function pnTaskOrder()
    {
        pnerificationToken();
        $dispatch = M('dispatch');
        $dispatch_task = M('dispatch_task');
        $data = array(
            'dispatch_id' => I('uid'),
            'task_id' => I('task_id'),
            'remark' => '完成1笔订单完成奖励2经验值和20帮币'
        );
        $ret = $dispatch->where(array('dispatch_id' => I('uid')))->field('comp_order_num')->find();
        if ($ret) {
            if ($ret['comp_order_num'] >= 1) {
                $rets = pnCreditScore(I('uid'), 2, 1, '完成1笔订单任务', '完成1笔订单任务奖励2经验值');
                if ($rets) {
                    $result = pnCoin(20, 1, I('uid'), '完成1笔订单任务', '完成1笔订单任务奖励20帮币');
                    if ($result) {
                        $data['is_complete'] = 'Y';
                        $data['complete_time'] = date('Y-m-d H:i:s');
                        $retss = $dispatch_task->add($data);
                        if ($retss) {
                            return RET_NO_V(1, "已完成任务");
                        } else {
                            return RET_NO_V(402, "添加记录失败");
                        }
                    } else {
                        return RET_NO_V(400, "增加帮币失败");
                    }
                } else {
                    return RET_NO_V(404, "增加经验值失败");
                }
            } else {
                $data['is_complete'] = 'N';
                $retss = $dispatch_task->add($data);
                if ($retss) {
                    return RET_NO_V(0, "未完成任务");
                } else {
                    return RET_NO_V(401, "添加记录失败");
                }
            }
        }
    }

    /**
     * @api {get} pnTask/token/:token/uid/:uid/ 跑客任务接口
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *      "retCode": 200,
     *       "retDesc": "返回成功",
     *     "retValue": {
     *      "notFinishTask": [], 未完成任务
     *     "finishTask": [], 已完成任务
     *      "notAcceptTask": [ 未接任务
     *
     *
     *    },
     * "retCode": 400,
     *       "retDesc": "无任务",
     *     "retValue": {
     *
     *    },
     */
    function pnTask()
    {
        // pnerificationToken();
        $task = M('task');
        $dispatch_task = M('dispatch_task');
        $notFinishTask = array();
        $finishTask = array();
        $task_id = array();
        $ret = $dispatch_task->where(array('dispatch_id' => I('uid')))->field('task_id,is_complete')->select();
        if ($ret) {
            for ($i = 0; $i < count($ret); $i++) {
                if ($ret[$i]["is_complete"] == 'N') {
                    $notFinish = $task->where(array('task_id' => $ret[$i]["task_id"]))->find();
                    array_push($notFinishTask, $notFinish);
                } else {
                    $finish = $task->where(array('task_id' => $ret[$i]["task_id"]))->find();
                    array_push($finishTask, $finish);
                }
                array_push($task_id, $ret[$i]["task_id"]);

            }
            $where['task_id'] = array('neq', $task_id);
            $notAccept = $task->select();
            $notAcceptTaska = array();
            for ($i = 0; $i < count($notAccept); $i++) {
                $tmp = true;
                for ($j = 0; $j < count($task_id); $j++) {
                    //dump($notAccept[$i]["task_id"]);
                    if ($notAccept[$i]["task_id"] == $task_id[$j]) {
                        $tmp = false;
                    }
                }
                if ($tmp) {
                    array_push($notAcceptTaska, $notAccept[$i]);
                }

            }

            $notAcceptTask = $notAcceptTaska;
        } else {
            $notAcceptTask = $task->select();
            if (!$notAcceptTask) {
                return RET_NO_V(400, "没有任务可完成");
            }
        }
        $ret = array(
            'notFinishTask' => $notFinishTask,
            'finishTask' => $finishTask,
            'notAcceptTask' => $notAcceptTask,
        );
        return RET(200, "返回成功", $ret);
    }

    /**
     * @api {get} pnWithdrawalRecord/token/:token/uid/:uid/cash_amount/:cash_amount/remark/:remark/ 提款申请
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiParam {int} cash_amount 提款金额
     * @apiParam {String} remark 说明,
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *      "retCode": 200,
     *       "retDesc": "提款申请成功",
     *
     * "retCode": 400,
     *       "retDesc": "提款申请失败",
     */
    function pnWithdrawalRecord()
    {
        pnerificationToken();
        $dispatch_cash = M('dispatch_cash');
        $dispatch = M('dispatch');
        $dispatch_balance = M('dispatch_balance');
        $cash_amount = I('cash_amount');
        $cash = $cash_amount / 100;
        if (($cash - floor($cash)) > 0) {
            return RET_NO_V(400, '请提取金额为100元或者100元的倍数！');
        }

        $cash_balance = $dispatch->where(array('dispatch_id' => I('uid')))->field('cash_balance,dispatch_name,is_sign')->find();
        if ($cash_balance['is_sign'] != '2') {
            return RET_NO_V(400, '跑客签约后才可提现！');
        }
        $getMoney = $cash_balance['cash_balance'] - C('deposit');
        if ($getMoney >= $cash_amount) {
            $dispatch_balance->startTrans();
            $nowBalance = $cash_balance['cash_balance'] - $cash_amount;

            $data = array(
                'trans_number' => I('trans_number'),
                'dispatch_id' => I('uid'),
                'cash_amount' => $cash_amount,
                'cash_time' => date('Y-m-d H:i:s'),
                'status' => 0,
                'remark' => I('remark')
            );
            $ret = $dispatch_cash->add($data);

            if (!$ret) {
                $dispatch_balance->rollback();
                return RET_NO_V(400, '提款申请失败');
            }
            $change_memo = '用户操作提现申请' . $cash_amount . '元';
            $remark = $cash_balance['dispatch_name'] . '的提现申请';
            $OrderDetail = pnOrderDetail(I('uid'), $cash_amount, 4, $change_memo, 0, $remark,$ret);

            $retss = $dispatch->where(array('dispatch_id' => I('uid')))->save(array('cash_balance' => $nowBalance));
            
            if ($retss && $ret && $OrderDetail) {
                $dispatch_balance->commit();
                return RET_NO_V(200, '提款申请成功');
            } else {
                $dispatch_balance->rollback();
                return RET_NO_V(400, '提款申请失败');
            }
        } else {
            return RET_NO_V(400, '提款金额要小于扣除押金后的余额');
        }
    }

    /**
     * @api {get} getPnNearby/token/:token/uid/:uid/ 获取附近跑客
     * @apiGroup pt
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     */

    function getPnNearby()
    {
        //鉴权
        verificationToken();
        $squares = returnSquarePoint(I('lon'), I('lat'));
        $company = M("company");
        $Model = M();
        $rets = $company->select();
        $ret_data = array();
        $count = 0;
        foreach ($rets as $key => $value) {
            //if($key>=1){
            $retd = "select dispatch_id as id,latitude as lat,longitude as lon from db_dispatch where work_status =1 and company_id=" . $value['company_id'] . " and latitude != 0 and latitude>{$squares['right-bottom']['lat']} and latitude<{$squares['left-top']['lat']} and longitude>{$squares['left-top']['lng']} and longitude<{$squares['right-bottom']['lng']} ";
            $ret_data['data'][$key]['company_id'] = $value['company_id'];
            $ret_data['data'][$key]['data'] = $Model->query($retd);
            if ($ret_data['data'][$key]['data'])
                $count = $count + count($ret_data['data'][$key]['data']);
            //}

        }
        $ret_data['count'] = $count;

        RET(1, "获取附近跑客成功！", $ret_data);
    }

    /**
     * @api {get} getUserRechargeDiscount/token/:token/uid/:uid/ 获取用户充值优惠策略数据
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     */

    function getUserRechargeDiscount()
    {
        $user_recharge_discount = M('user_recharge_discount');
        $ret = $user_recharge_discount->select();
        if ($ret) {
            return RET(200, '获取用户充值优惠策略数据成功', $ret);
        } else {
            return RET_NO_V(400, '获取用户充值优惠策略数据失败');
        }
    }

    /**
     * @api {get} pnRecommendSet/token/:token/uid/:uid/cash_account_name/:cash_account_name/cash_account/:cash_account/ 跑客支付宝体现账号设置
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiParam {String} cash_account_name 提现账号名称
     * @apiParam {String} cash_account 提现账号,
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *      "retCode": 200,
     *       "retDesc": "账号设置成功",
     *
     * "retCode": 400,
     *       "retDesc": "账号设置失败",
     */
    function pnRecommendSet()
    {
        pnerificationToken();
        $recommend_set = M("recommend_set");
        $datastatus = $recommend_set->where(array('dispatch_id' => I('uid')))->find();
        if ($datastatus) {
            $rets = $recommend_set->where(array('dispatch_id' => I('uid')))->save(array('cash_account_name' => I('cash_account_name'), 'cash_account' => I('cash_account')));
            if ($rets) {
                RET_NO_V(200, "账号设置成功");
            } else {
                RET_NO_V(400, "账号设置失败");
            }
        } else {
            $ret = $recommend_set->add(array('dispatch_id' => I('uid'), 'cash_account_name' => I('cash_account_name'), 'cash_account' => I('cash_account')));
            if ($ret) {
                RET_NO_V(200, "账号设置成功");
            } else {
                RET_NO_V(400, "账号设置失败");
            }
        }

    }

    /**
     * @api {get} pnRecommendSet/token/:token/uid/:uid/ 跑客支付宝体现账号获取设置
     * @apiGroup PN
     *
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *      "retCode": 200,
     *       "retDesc": "获取账号设置成功",
     *
     * "retCode": 400,
     *       "retDesc": "获取账号设置失败",
     */
    function pnRecommendGetSet()
    {
        pnerificationToken();
        $recommend_set = M("recommend_set");
        $data = $recommend_set->where(array('dispatch_id' => I('uid')))->find();
        if ($data) {
            RET(200, "获取账号设置成功", $data);
        } else {

            $recommend_set_data = array(
                'dispatch_id' => I('uid'),
                'cash_account_type' => 2,
                'hold_light' => 1,
                'is_incubator' => 1
            );
            $ret = $recommend_set->add($recommend_set_data);
            if ($ret) {
                RET(200, "获取账号设置成功", $recommend_set->where(array('dispatch_id' => I('uid')))->find());
            } else {
                RET_NO_V(400, "获取账号设置失败");
            }

        }
    }

    function test1()
    {
        $pricing_tactics = M('pricing_tactics');
        $data = array(
            "mileage" => array(                   //里程费
                array(
                    "title" => "2公里",
                    "kilometre" => 2,             //阶段最高公里数
                    "money" => 8,                 //阶段最高钱数
                    "money_title" => "8.0元",      //阶段最高钱数文字
                    "pricePer" => 4                   //每公里单价
                ),
                array(
                    "title" => "3公里",
                    "kilometre" => 3,
                    "money" => 12,
                    "money_title" => "12.0元",
                    "pricePer" => 4
                ),
                array(
                    "title" => "3公里-10公里",
                    "kilometre" => 10,
                    "money" => 19,
                    "money_title" => "1元/公里",
                    "pricePer" => 1
                ),
                array(
                    "title" => "10公里-30公里",
                    "kilometre" => 30,
                    "money" => 59,
                    "money_title" => "2元/公里",
                    "pricePer" => 2
                ),
                array(
                    "title" => "30公里以外",
                    "kilometre" => 10000,
                    "money" => 100000,
                    "money_title" => "3元/公里",
                    "pricePer" => 3
                ),
            ),
            "line_up" => array(                  //排队费用
                array(
                    "title" => "起步价(含60分钟)",
                    "timemin" => 60,             //阶段起步最高分钟数
                    "money" => 20,                 //阶段起步最高钱数
                    "money_title" => "20.0元",      //阶段最高钱数文字
                    "pricePer" => 10                   //每半小时单价
                ),
                array(
                    "title" => "1-10小时",
                    "timemin" => 600,             //阶段最高分钟数
                    "money" => 200,                 //阶段最高钱数
                    "money_title" => "10.0元/30分钟",      //阶段最高钱数文字
                    "pricePer" => 10                   //每半小时单价
                ),
                array(
                    "title" => "延长排队(线下支付)",
                    "timemin" => 60000,             //阶段最高公里数
                    "money" => 20000,                 //阶段最高钱数
                    "money_title" => "10.0元/30分钟",      //阶段最高钱数文字
                    "pricePer" => 10                   //每半小时单价
                ),
            ),
            "night" => array(                     //夜间补助
                array(
                    "title" => "22:00-24:00",
                    "startTime" => "22:00",
                    "endTime" => "24:00",
                    "addMoney" => 5,
                    "money_title" => "每单加价5元",
                ),
                array(
                    "title" => "00:00-07:00",
                    "startTime" => "00:00",
                    "endTime" => "07:00",
                    "addMoney" => 10,
                    "money_title" => "每单加价10元",
                ),
            ),
            "temporary" => array(                 //临时加价
                "addtimes" => 1.2
            ),
            "is_starting_price" => array(         //起步价冗余字段
                "mileageKilometre" => 3,             //计费实际起步公里
                "mileageMoney" => 12,                 //计费实际起步费
                "lineTime" => 30,                 //排队起步计费半小时
                "lineKoney" => 10.0,              //排队起步费
            )
        );
        $data1 = json_encode($data);
        $pricing_tactics->where(array('pid' => 1))->save(array('tactics_array' => $data1));
    }

    /**
     * @api {get} getQueueType/token/:token/uid/:uid/set_id/:set_id 获取保价加急排队集合
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 跑腿token,每次登录都会更改.
     * @apiParam {Int} set_id 1:保价设置 2：加急设置 3：排队类型设置 4:排队时长设置
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * {
     * "retCode": 200,
     * "retDesc": "数据获取成功",
     * "retValue": "[{\"text\":\"5\\u5143 30\\u5206\\u949f\\u8fbe\",\"status\":\"normal\"},{\"text\":\"3\\u5143 40\\u5206\\u949f\\u8fbe\",\"status\":\"normal\"},{\"text\":\"2\\u5143 50\\u5206\\u949f\\u8fbe\",\"status\":\"normal\"},{\"text\":\"1\\u5143 60\\u5206\\u949f\\u8fbe\",\"status\":\"normal\"}]"
     * }
     **/
    function getQueueType()
    {
        //校验token
        verificationToken();
        $set_id = I('set_id');
        if (!$set_id)
            return RET_NO_V(400, "参数为空");
        $sys_set_db = M('sys_set');
        $ret = $sys_set_db->where('set_id=' . $set_id)->find();

        if ($ret) {
            RET(200, "数据获取成功", $ret['collection_cost']);
        } else {
            RET_NO_V(400, "数据获取失败");
        }
    }

    /**
     * @api {get} cancleOrderOption/token/:token/uid/:uid/order_number/:order_number/cancel_reason_id/:cancel_reason_id/cancel_party:cancel_party 取消订单操作
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiParam {String} order_number 订单号 必填
     * @apiParam {Int} cancel_reason_id 退款理由 可选
     * @apiParam {Int} cancel_party 退款方  1、用户取消，2、派单员取消 可选
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * {
     * "retCode": 200,
     * "retDesc": "退款成功",
     * "retValue": ""
     * }
     **/
    function cancleOrderOption()
    {
        //校验token
        $order_number = I('order_number');
        $user_id = I('uid');
        $cancel_reason_id = I('cancel_reason_id', 0);
        $cancel_party = I('cancel_party', 1);

        if ($cancel_party == 2)
            pnerificationToken();
        else
            verificationToken();

        if (!$order_number || !$user_id)
            return RET_NO_V(400, "参数为空");

        //取得订单数据
        $order_db = M('order');
        if ($cancel_party == 1)
            $order_obj = $order_db->where(" order_number = '" . $order_number . "' and user_id = " . $user_id)->find();
        else
            $order_obj = $order_db->where(" order_number = '" . $order_number . "' and dispatch_id = " . $user_id)->find();
//        dump($order_db->getLastSql());
//        dump('获取订单信息：');
        if (!$order_obj)
            return RET_NO_V(400, "订单号有误");
//        dump($order_obj);

        $order_db->startTrans();
//        dump('取消方：');
        $status = $order_obj['status'];
        //跑客取消,扣跑客五元，订单重发，告知用户，退出。
        if ($cancel_party == 2) {
//            dump('取消方是跑客：'.$cancel_party);
            $option_ret = pnCancleOrderOptions($order_obj['dispatch_id'], $user_id, $order_obj['order_id'], $order_obj['order_amount'], $order_number);//跑客取消订单综合处理
//           dump('综合处理结果'.$option_ret);
            $add_cancle_ret = addOrderCancle($order_obj['order_id'], $order_obj['user_id'], $order_obj['dispatch_id'], $status, '2', '跑客自主取消');//维护中间表---取消订单表
            $order_upret = $order_db->where(array('order_id' => $order_obj['order_id']))->setField(array('dispatch_id' => 0, 'status' => 1, 'dispatch_end_time' => null, 'dispatch_get_money' => null));

            $order_upret = M('order_resmsm')->where(array('order_id' => $order_obj['order_id']))->setField(array('is_success' => '0', 'is_send' => '0', 'order_time' => date('Y-m-d H:i:s', time())));//修改中间表的状态、时间，为的是再次重发3次

            $cancle_ret = cancle_order_repeat($order_obj['order_id']); //3、订单重发，退出退单流程

            if ($add_cancle_ret && $option_ret && $order_upret && $order_upret) {
                $order_db->commit();
                return RET(200, "跑客取消订单" . $order_number . "成功", $cancle_ret);
            } else {
                $order_db->rollback();
                return RET_NO_V(400, "跑客取消订单" . $order_number . "失败");
            }
        }
//        dump('取消方是用户：'.$cancel_party);

        //获取支付信息
        $recharge_db = M('order_pay');
        $pay_obj = $recharge_db->where(' order_id=' . $order_obj['order_id'])
            ->field('pay_amount,pay_number,pay_id')->find();
//        dump('获取订单支付信息：');
//        dump($pay_obj);
        if (!$pay_obj)
            return RET_NO_V(400, "订单支付信息有误");


//        dump('已支付订单处理：');
//        dump('支付方式：'.$order_obj['pay_method']);
//        dump('订单状态：'.$status);

        //有优惠券处理
        $user_cancle_fine = C('user_cancle_fine');//用户取消订单违约金
        $return_amount = (float)$order_obj['order_amount'];//退款金额
        $fine_amount = 0.00;//应扣罚金
        $coupin_msg = "";//优惠券备注
        $is_used = 1;
        if ($order_obj['coupon_id']) {//有优惠券不退回，看优惠券的金额，取消或再扣余额
//            dump('有优惠券');
            switch ($status) {
                case 0:
                    $is_used = M('user_coupon')->where(array('user_coupon_id' => $order_obj['coupon_id']))->save(array('is_used' => 1));
//                    dump('优惠券退还结果：'.$is_used);
                    break;
                case 1:
                    $user_coupon_db = M('user_coupon');
                    $user_coupon = $user_coupon_db->where(array('user_coupon_id' => $order_obj['coupon_id']))->find();
//                        dump($user_coupon['coupon_value']);
                    if ($user_coupon['coupon_type'] == 1)
                        $coupon_amount = $user_coupon['coupon_value'];//优惠的金额
                    if ($user_coupon['coupon_type'] == 2)
                        $coupon_amount = $order_obj['order_amount'] * ((100 - $user_coupon['min_deduct_amount']) / 100);//优惠的金额

                    $is_used = $user_coupon_db->where(array('user_coupon_id' => $order_obj['coupon_id']))->save(array('is_used' => 1));
                    $coupin_msg = '，使用优惠券' . number_format($coupon_amount, 2, '.', ',') . '元，退还优惠券';
//                    dump(M('user_coupon')->getLastSql());
//                    dump('优惠券退还结果：'.$is_used);
                    break;
                case 2:
                    //用户取消
                    $user_coupon_db = M('user_coupon');
                    $user_coupon = $user_coupon_db->where(array('user_coupon_id' => $order_obj['coupon_id']))->find();
//                        dump($user_coupon['coupon_value']);
                    if ($user_coupon['coupon_type'] == 1)
                        $coupon_amount = $user_coupon['coupon_value'];//优惠的金额
                    if ($user_coupon['coupon_type'] == 2)
                        $coupon_amount = $order_obj['order_amount'] * ((100 - $user_coupon['min_deduct_amount']) / 100);//优惠的金额
//                        dump('优惠金额:'.$coupon_amount);
                    //优惠金额 < 惩罚金额  优惠券是已使用状态，不用处理
                    if ($coupon_amount < $user_cancle_fine) {
                        $fine_amount = $user_cancle_fine - $coupon_amount;//应扣罚金
                        $return_amount = $pay_obj['pay_amount'] - $fine_amount;//退款金额
                    } else {
                        $fine_amount = 0.00;
                        $return_amount = $pay_obj['pay_amount'];//退款金额
                    }
                    $coupin_msg = '，' . number_format($coupon_amount, 2, '.', ',') . '元优惠券失效';
//                    dump('优惠券不退还');
                    break;
                default:
                    break;
            }
        } else {
//            dump('没有优惠券');
            $fine_amount = $user_cancle_fine;//应扣罚金
            $return_amount = $order_obj['order_amount'] - $user_cancle_fine;
        }
//        $fine_amount=number_format($fine_amount, 2, '.', '');
//        $return_amount=number_format($return_amount, 2, '.', ',');

//       dump('订单状态：'.$status.'，支付方式：'.$order_obj['pay_method']);
//exit;
        //订单接单前、支付后的处理
        switch ($status) {
            case 0://未支付订单，可以取消订单，不用退款、退优惠券
                create_user_message($user_id, '取消订单', '您取消了未支付订单(' . $order_number . ')', '您取消了未支付订单(' . $order_number . ')');
                break;
            case 1://已支付未接单，可以取消订单，退优惠券、退款
//                dump("付款金额".$pay_obj['pay_amount']);
                if (!$pay_obj || $pay_obj['pay_amount'] < 0)
                    return RET_NO_V(400, "退款金额必须大于0");

                if ($pay_obj['pay_amount'] > $order_obj['order_amount'])
                    return RET_NO_V(400, "退款金额必须小于订单金额");

                if ($order_obj['pay_method'] == 1) {
                    $remark_msg = '您取消了订单(' . $order_number . ')，支付宝支付订单金额是' . $pay_obj['pay_amount'] . '元' . $coupin_msg . '，退款到用户余额 ' . $pay_obj['pay_amount'] . '元';
                } elseif ($order_obj['pay_method'] == 2) {
                    $remark_msg = '您取消了订单(' . $order_number . ')，微信支付订单金额是' . $pay_obj['pay_amount'] . '元' . $coupin_msg . '，退款到用户余额 ' . $pay_obj['pay_amount'] . '元';
                } elseif ($order_obj['pay_method'] == 3) {
                    $remark_msg = '您取消了订单(' . $order_number . ')，钱包支付订单金额是' . $pay_obj['pay_amount'] . '元' . $coupin_msg . '，退款到用户余额 ' . $pay_obj['pay_amount'] . '元';
                }
//                //如果是免单2016年11月08日19:47:24
//                //修改人陈亚磊
//                if($order_obj['real_amount'] !="0.00"){
//                    $return_amount_ret = return_amount_option($order_obj['pay_method'],$order_number,$pay_obj['pay_number'],$user_id,$order_obj['order_id'], $pay_obj['pay_amount'],$remark3,$remark_msg);
//                    if( !$return_amount_ret){
//                        $order_db->rollback();
//                        return RET_NO_V(400, "用户取消订单".$order_number."失败");
//                    }
//                }
//                dump($remark_msg);
                $dispatch_blance_ret = 1;
                $purse_ret = 1;
                if (floatval($order_obj['real_amount']) != 0.00) {

//                dump('用户表余额字段值增加'.$order_obj['real_amount'] . '元');
//                dump($dispatch_blance_ret);
                    $purse_ret = userPurseLog($user_id, 3, $order_obj['real_amount'], $remark_msg, 0, $order_obj['order_id']);//用户钱包明细表 增加记录
                    $dispatch_blance_ret = update_user_dispatch_blance($user_id, 1, $order_obj['real_amount']);//增加 用户表或跑客表的 余额字段  的值
//                dump('用户钱包明细表'.$order_obj['real_amount'] . '元');
//                dump($purse_ret);
                } else {
                    $remark_msg = '您取消了订单(' . $order_number . ')，此单是免单订单，优惠券退还 ';
                }
                $msg_ret = create_user_message($user_id, '取消订单', $remark_msg, $remark_msg);
//                dump('msg_ret:'.$msg_ret);
                break;
            case 2://已接单未到达，可以取消订单，不退优惠券，退款但需要罚款
//                dump("付款金额".$pay_obj['pay_amount']);
                if (!$pay_obj || $return_amount < 0)
                    return RET_NO_V(400, "退款金额必须大于0");

                if ($pay_obj['pay_amount'] < $return_amount)
                    return RET_NO_V(400, "退款金额必须小于订单金额");

//                dump('订单金额：'.$order_obj['order_amount']);
//                dump('应扣罚金：'.$fine_amount);
//                dump('应退款金额：'.$return_amount);
                $fine_msg = '';
                if ($fine_amount > 0.00)
                    $fine_msg = ',扣除' . number_format($fine_amount, 2, '.', ',') . '元违约金';
                if ($order_obj['pay_method'] == 1) {
                    $remark_msg = '订单（' . $order_number . '）被跑客抢单后您取消了订单，支付宝支付订单金额是' . $pay_obj['pay_amount'] . '元' . $coupin_msg . $fine_msg . '，退回到用户余额' . number_format($return_amount, 2, '.', ',') . '元';
                } elseif ($order_obj['pay_method'] == 2) {
                    $remark_msg = '订单（' . $order_number . '）被跑客抢单后您取消了订单，微信支付订单金额是' . $pay_obj['pay_amount'] . '元' . $coupin_msg . $fine_msg . '，退回到用户余额' . number_format($return_amount, 2, '.', ',') . '元';
                } elseif ($order_obj['pay_method'] == 3) {
                    $remark_msg = '订单（' . $order_number . '）被跑客抢单后您取消了订单，钱包支付订单金额是' . $pay_obj['pay_amount'] . '元' . $coupin_msg . $fine_msg . '，退款到用户余额' . number_format($return_amount, 2, '.', ',') . '元';
                }
//                dump('第三方支付备注：'.$remark3);
//                dump('消息备注：'.$remark_msg);
//                $return_amount_ret = return_amount_option($order_obj['pay_method'],$order_number,$pay_obj['pay_number'],$user_id,$order_obj['order_id'], $return_amount,$remark3,$remark_msg);
                $dispatch_blance_ret = 1;
                $purse_ret = 1;
                if (floatval($order_obj['real_amount']) != 0.00) {

//            dump('用户表余额字段值增加'.$return_amount . '元');
//            dump($dispatch_blance_ret);
                    $purse_ret = userPurseLog($user_id, 3, $return_amount, $remark_msg, 0, $order_obj['order_id']);//用户钱包明细表 增加记录
                    $dispatch_blance_ret = update_user_dispatch_blance($user_id, 1, $return_amount);//增加 用户表或跑客表的 余额字段  的值
//              dump('用户钱包明细表'.$return_amount . '元');
//                dump($purse_ret);
                } else {
                    $remark_msg = '订单（' . $order_number . '）被跑客抢单后您取消了订单，优惠券失效';
                }
                $msg_ret = create_user_message($user_id, '取消订单', $remark_msg, $remark_msg);
//                dump('msg_ret'.$msg_ret);
                $sys_ret = 1;
//                var_dump($fine_amount);
                if ($fine_amount > 0.00) {//罚金>0 ; 即优惠券金额 < 罚金金额,需要扣除用户现金金额
//                    dump('罚金大于0：'.$fine_amount);
                    $sys_ret = create_systrunover($user_id, $order_obj['dispatch_id'], $order_obj['order_amount'], $fine_amount, $order_obj['order_id'], '2', $order_obj['user_id'] . '用户违约金');//罚金记入平台
//                    dump('罚金记入平台'.$fine_amount . '元');
//                    dump($sys_ret);
                }

                //奖励跑客500帮币
                $coin = C('user_cancle_reward');//用户取消订单的奖励
                $pncoin_ret = pnCoin($coin, 1, $order_obj['dispatch_id'], '您接的订单（' . $order_number . '），被用户取消后奖励' . $coin . '帮币', '用户取消订单后的奖励');
                //通知跑客，用户取消订单，奖励跑客500帮币
                $pncoin_msg_ret = create_dispatch_message($order_obj['dispatch_id'], '您接的订单已被用户取消', '您接的订单（' . $order_number . '）已被用户取消', '您接的订单（' . $order_number . '），已被用户取消，奖励您' . $coin . '帮币');
                //每天首单已扣除保险费，用户退单，需要退回保险费。
//                $insu_ret = return_dispatch_insurance($order_obj['dispatch_id'], $order_obj['order_id'], 2);
                //====临时取消保险费=======2016-12-29 19:05:50
                //$insu_ret = dispatch_insurance_options($order_obj['dispatch_id'], $order_obj['order_id'], 2, 9, '退还保险费', '您今天接的第一个订单（' . $order_number . '）已被用户取消，退还保险费2.00元', '您今天接的第一个订单（' . $order_number . '）已被用户取消，退还您保险费2.00元');
//                dump('首单首笔退单保险金结果'.$insu_ret);
                //退还保险金通知跑客
//                $return_insurance_msg=1;
//                if($insu_ret==1)//保险退成功了，通知跑客
//                    $return_insurance_msg = create_dispatch_message($order_obj['dispatch_id'],'您今天接的第一个订单已被您取消',"您今天接的第一个订单已被您取消",'您今天接的第一单订单已被您取消，退还您保险费2.00元');
//                dump('首单首笔退单保险金通知消息结果'.$return_insurance_msg);
//                dump('帮币：'.$coin . '元');
//                dump($pncoin_ret);
                //dump('sys_ret:'.$sys_ret.'pncoin_ret'.$pncoin_ret.'pncoin_msg_ret'.$pncoin_msg_ret.'insu_ret'.$insu_ret.'return_insurance_msg'.$return_insurance_msg.'return_amount_ret'.$return_amount_ret);

                if (!$dispatch_blance_ret || !$purse_ret || !$sys_ret || !$pncoin_ret || !$pncoin_msg_ret || !$msg_ret) {
                    $order_db->rollback();
                    return RET_NO_V(400, "用户取消订单" . $order_number . "失败");
                }
                break;
            case 7:
                return RET_NO_V(400, "订单已经完成，不能取消");
                break;
            case 9:
                return RET_NO_V(400, "订单已经取消");
                break;
            default:
                return RET_NO_V(400, "订单已经在进行中，不能取消");
                break;
        }
//        exit;
        //订单支付表处理-db_order_pay
        $pay_upret = $recharge_db->where('pay_id=' . $pay_obj['pay_id'])->setField('return_status', 1);
//        dump('订单支付表 支付状态处理：');
//        dump($pay_upret);
        //订单状态的修改
//        dump('修改订单id：'.$order_obj['order_id']);
        $data = array('status' => 9, 'cancel_time' => date('Y-m-d H:i:s', time()), 'cancel_reason_id' => $cancel_reason_id, 'cancel_party' => $cancel_party);
        $order_upret = $order_db->where('order_id = ' . $order_obj['order_id'])->save($data);
//        dump('订单状态的修改处理：');
//        dump($order_upret);

        //退款成功,删除中间表order_resmsm
        $rems_db = M('order_resmsm');
        $del_ret = $rems_db->where('order_id=' . $order_obj['order_id'])->delete();
//        dump('删除中间表处理：');
//        dump($del_ret);

        //则写入用户消息
//        $msg_ret = create_user_message($user_id,'订单已取消','订单已取消','您的订单已被您取消，如需要请再次下单');
//        dump('写入用户消息：');
//        dump($msg_ret);
        $add_cancle_ret = addOrderCancle($order_obj['order_id'], $order_obj['user_id'], $order_obj['dispatch_id'], $status, '1', '用户取消');//维护中间表---取消订单表

        if ($add_cancle_ret && $order_upret && $pay_upret && $del_ret && $is_used) {
//            dump('订单取消成功');
            $order_db->commit();
            return RET_NO_V(200, '订单取消成功');
        } else {
            $order_db->rollback();
            return RET_NO_V(400, '订单取消失败');
        }
    }

    function returnMoneytest()
    {
        //退款测试
//        vendor("alipay_api.aop.test.TestImage");
//
//        $test = new \TestImage();
//
//        $test->load();
//        exit;

        $return_ret = returnMoney('CZ_TRADENO2016822115015437580', '2016092221001004080202256201', 0.01, '未接订单退款');//充值退款测试

        dump($return_ret);
        if ($return_ret)
            RET_NO_V(200, "退款成功");
        else
            RET_NO_V(400, "退款失败");

    }

    function pndispatch()
    {

    }

    /**
     * @api {get} pnCompanys/token/:token/uid/:uid/ 选择跑客团队
     * @apiGroup PN
     *
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * {
     * "retCode": 200,
     * "retDesc": "退款成功",
     * "retValue": [
     *          {
     *              "company_id": "1",
     *              "company_name": "恒盛团队"
     *          },
     *          {
     *              "company_id": "2",
     *              "company_name": "多跑团队"
     *          }
     *              ]
     * }
     **/
    function pnCompanys()
    {
        //校验token
        //verificationToken();
        $com_db = M('company');
        $ret = $com_db->where('company_id != 1 ')->order('sort asc')->select();
        //$ret = $com_db->select();
        if ($ret)
            RET(200, '获取数据成功', $ret);
        else
            RET_NO_V(400, '获取数据失败');
    }

    /**
     * @api {get} isAddPrice/token/:token/uid/:uid/cityId/:cityId 判断是否有加价
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiParam {Int} cityId 城市id.必填
     * @apiParam {String} appointmentTime 预约时间 .选填
     *  *@apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * {
     * "retCode": 200,
     * "retDesc": "返回成功",
     * "retValue": [
     *           "startTime": "22：00",  //夜晚加价开始时间
     *  "endTime": "24：00", //夜晚加价结束时间
     *  "addMoney": "5", //夜晚加价的金额
     *  "addtimes": "1.2",//临时加价的金额
     *              ]
     * }
     **/
    function isAddPrice()
    {
        verificationToken();
        $pricing_tactics = M("pricing_tactics");
        $ret = $pricing_tactics->where(array('city_id' => I('cityId')))->field('tactics_array')->find();
        $rets['startTime'] = null;
        $rets['endTime'] = null;
        $rets['addMoney'] = null;
        $rets['addtimes'] = null;
        if ($ret['tactics_array']) {
            $tactics_array = json_decode($ret['tactics_array'], TRUE);
            $night = $tactics_array['night'];
            $date = null;
            /*$time = "2016-1-10 23:23";
            $date = substr($time,-5,5);
            dump($date);*/
            if (I('appointmentTime')) {
                $date = substr(I('appointmentTime'), -5, 5);
            } else {
                $date = date('H:i');
            }
            for ($i = 0; $i < count($night); $i++) {
                $startTime = $night[$i]['startTime'];
                $endTime = $night[$i]['endTime'];
                if ($startTime <= $date) {
                    if ($endTime > $date) {
                        $rets['startTime'] = $startTime;
                        $rets['endTime'] = $endTime;
                        $rets['addMoney'] = $night[$i]['addMoney'];
                        break;
                    }
                }
            }
            $temporary = $tactics_array['temporary'];
            if ($temporary["addtimes"] > 1) {
                $rets['addtimes'] = $temporary["addtimes"];
            }
        }
        return RET(200, "返回成功", $rets);
    }

    /**
     * @api {get} getResTypes/token/:token/uid/:uid/type/:type 获取物品类别等
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiParam {Int} type 类别     1:取送类别，2：代买类别，3：排队类别.必填
     *  *@apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * {
     * "retCode": 200,
     * "retDesc": "返回成功",
     * "retValue": [
     *      {
     *          "res_type_id": "27",   //主键 id
     *          "res_type": "美食",     //类型名称
     *          "insur_account": "100.00", //保价金额
     *          "sort": "1",              //排序
     *          "type": "1"       //类别   1:取送类别，2：代买类别，3：排队类别.必填
     *      },
     *      {
     *          "res_type_id": "28",
     *          "res_type": "糕点",
     *          "insur_account": "100.00",
     *          "sort": "2",
     *          "type": "1"
     *      }
     *              ]
     **/
    function getResTypes()
    {
        //verificationToken();
        $type = I("type");

        if (!$type)
            return RET_NO_V(400, "参数为空");

        $res_type_db = M("res_type");
        $rets = $res_type_db->where(array('type' => $type))->order('sort')->select();
//        dump($rets);
//        die;
        if ($rets) {
            return RET(200, "返回成功", $rets);
        } else
            return RET_NO_V(400, "返回失败");
    }

    /**
     * @api {get} getEvalUserInfo/token/:token/uid/:uid/order_id/:order_id/user_type/:user_type 评价时初始化头像等信息
     * @apiGroup pt PN
     * @apiParam {Int} uid       用户唯一ID. 必填
     * @apiParam {String} token  跑腿token,每次登录都会更改. 必填
     * @apiParam {Int} user_type 被评价人用户类别     1:跑客（必填），2：普通用户（必填）
     * @apiParam {Int} order_id  订单id .必填
     *  *@apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * user_type=1
     * {
     * "retCode": 200,
     * "retDesc": "返回成功",
     * "retValue": [{
     *      "user_id": "61",
     *      "user_name": "15738364224",
     *      "avatar": "Uploads/userHeadImg/2016/09/18/201609181724201126356874.jpg",
     *      "level_name": "普通会员"
     *    } ]
     * user_type=2
     * {
     * "retCode": 200,
     * "retDesc": "返回成功",
     * "retValue": [{
     *      "dispatch_id": "33",
     *      "dispatch_name": "高磊",
     *      "avatar": "Uploads/pnHeadImg/2016/09/28/20160928171021504719762.jpg",
     *      "level_name": "跑客一级"
     *    } ]
     **/
    function getEvalUserInfo()
    {

        $user_type = I("user_type");
        $order_id = I('order_id');
        $uid = I('uid');
        if (!$user_type || !$order_id)
            return RET_NO_V(400, "参数为空");
        $order_db = M('order o');

        if ($user_type == 2) {
            pnerificationToken();
            $order_obj = $order_db->field('au.user_id,au.user_name,au.avatar,ul.level_name')
                ->join('join db_app_users au on o.user_id = au.user_id')
                ->join('join db_user_level ul on au.user_level_id=ul.user_level_id')
                ->where('order_id = ' . $order_id . ' and o.dispatch_id=' . $uid . ' and status=7')
                ->find();
            if ($order_obj)
                return RET(200, '获取数据成功', $order_obj);
            else
                return RET_NO_V(400, '获取数据失败');
        }
        if ($user_type == 1) {
            verificationToken();
            $order_obj = $order_db->field('du.dispatch_id,du.dispatch_name,du.avatar,dl.level_name')
                ->join('join db_dispatch du on du.dispatch_id = o.dispatch_id')
                ->join('join db_dispatch_level dl on du.dispatch_level_id = dl.dispatch_level_id')
                ->where('order_id = ' . $order_id . ' and o.user_id = ' . $uid . ' and status=7')
                ->find();
            if ($order_obj)
                return RET(200, '获取数据成功', $order_obj);
            else
                return RET_NO_V(400, '获取数据失败');
        }
    }

    /**
     * @api {get} saveOrderEvalInfo/token/:token/uid/:uid/order_id/:order_id/user_type/:user_type/eval_value/:eval_value/eval_target/:eval_target 保存评价值
     * @apiGroup pt PN
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiParam {Int} user_type 被评价用户类别     1:跑客（必填），2：普通用户（必填）
     * @apiParam {Int} order_id 订单id .必填
     * @apiParam {Int} eval_value 普通用户评价（星星数）
     * @apiParam {String} eval_target 普通用户评价的标签
     *
     *  *@apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     * user_type=1
     * {
     * "retCode": 200,
     * "retDesc": "返回成功",
     * "retValue": [{
     *      "user_id": "61",
     *      "user_name": "15738364224",
     *      "avatar": "Uploads/userHeadImg/2016/09/18/201609181724201126356874.jpg",
     *      "level_name": "普通会员"
     *    } ]
     * user_type=2
     * {
     * "retCode": 200,
     * "retDesc": "保存评价成功",
     * "retValue": ""
     * }
     **/
    function saveOrderEvalInfo()
    {

        $user_type = I("user_type");
        $order_id = I('order_id');
        $uid = I('uid');

        if (!$user_type || !$order_id)
            return RET_NO_V(404, "参数为空");

        $order_db = M('order o');

        $order_db->startTrans();
        //给跑客评价
        if ($user_type == 1) {
//            verificationToken();
            $order_obj = $order_db->field('user_eval_value,dispatch_id')
                ->where('order_id=' . $order_id . ' and user_id=' . $uid . ' and status=7 and user_eval_value is null')->find();
            if ($order_obj['user_eval_value']) {
                return RET_NO_V(405, "无订单需要评价");
            }
            $data['user_eval_value'] = I("eval_value");
            $data['user_eval_target'] = I('eval_target');

            $eval_ret = $order_db->where('order_id=' . $order_id . ' and user_id=' . $uid . ' and status=7')->setField($data);

            if ($eval_ret) {
                $ret = M("order")->where(array("order_id" => $order_id))->field("dispatch_id")->find();

                if ($ret) {

                    $return = pnPraise(I("eval_value"), $order_obj["dispatch_id"]);

                    if ($return) {
                        $eval_value = I("eval_value");

                        $pnCoin_ret = null;
                        if ($eval_value == 5) {

                            $pnCoin_ret = pnCoin(C('order_coin_add'), 1, $order_obj["dispatch_id"], "五星好评奖励" . C('order_coin_add') . '个帮币', "五星好评奖励");

                        } else if ($eval_value <= 3) {
                            $pnCoin_ret = pnCoin(C('order_coin_sub'), 2, $order_obj["dispatch_id"], "完成订单," . I("eval_value") . '星好评，扣除' . C('order_coin_sub') . '个帮币', "完成订单3个星级及以下好评扣除帮币");
                        }

                        if ($eval_value != 4 && !$pnCoin_ret) {
                            $order_db->rollback();
                            return RET_NO_V(400, '跑客帮币修改失败');
                        } else {
                            $order_db->commit();
                            return RET(200, '保存评价成功');
                        }
                    } else {
                        $order_db->rollback();
                        return RET_NO_V(402, '跑客好评率修改失败');
                    }
                } else {
                    $order_db->rollback();
                    return RET_NO_V(400, '保存评价失败');
                }
            }
        }
        //给普通用户评价
        if ($user_type == 2) {
            $order_obj = $order_db->field('disp_eval_value')
                ->where('order_id=' . $order_id . ' and dispatch_id=' . $uid . ' and status=7 and disp_eval_value is null')->find();

            if ($order_obj['disp_eval_value']) {
                return RET_NO_V(405, "无订单需要评价");
            }
            $data['disp_eval_value'] = I("eval_value");
            $data['disp_eval_target'] = I('eval_target');

            $eval_ret = $order_db->where('order_id=' . $order_id . ' and dispatch_id=' . $uid . ' and status=7')->setField($data);
            if ($eval_ret) {
                $order_db->commit();
                return RET(200, '保存评价成功');
            } else {
                $order_db->rollback();
                return RET_NO_V(400, '保存评价失败');
            }

        }
    }

    /**
     * @api {get} userBalancePay/token/:token/uid/:uid/order_id/:order_id/out_trade_no/:out_trade_no 用户余额支付
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} topnRobOrderken 跑腿token,每次登录都会更改. 必填
     * @apiParam {Int} order_id 订单id .必填
     * @apiParam {String}out_trade_no  商户唯一订单号 选填
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     * {
     * "retCode": 200,
     * "retDesc": "订单余额支付成功",
     * "retValue": ""
     * }
     **/
    function userBalancePay()
    {
        verificationToken();
        $order_id = I('order_id');
        $uid = I('uid');
        $out_trade_no = I('out_trade_no');

        if (!$uid || !$order_id)
            return RET_NO_V(400, '参数为空');

        $order_db = M('order');
        $order_pay = M('order_pay');
        $order_obj = $order_db->field('real_amount,order_number,order_amount,coupon_id')
            ->where(" order_id = '" . $order_id . "' and user_id = " . $uid . ' and pay_status=0 and pay_method=3')
            ->find();

        if (!$order_obj)
            return RET_NO_V(400, "订单号有误");
        $order_db->startTrans();
        $real_amount = $order_obj['real_amount'];
        $change_remark = '订单 ' . $order_obj['order_number'] . ' 用户余额支付 ' . $real_amount . '元';
        if ($real_amount == "0.00" && $order_obj['coupon_id']) {
            //反查优惠信息表
            $coupon_info = M("user_coupon");
            $cou_ret = $coupon_info->field('coupon_value,coupon_type')->where("user_coupon_id=" . $order_obj['coupon_id'] . " and valid_end_time >= sysdate()")->find();

            if ($cou_ret) {
                $cou_amount = $cou_ret['coupon_value'];//抵扣的钱数
                if ((float)$cou_amount >= (float)$order_obj['order_amount']) {
                    $change_remark = '订单(' . $order_obj['order_number'] . ')使用优惠券抵扣，此单免单';
                } else {
                    return RET_NO_V(400, "优惠金额有误");
                }
            } else {
                return RET_NO_V(400, "优惠金额有误");
            }
        } else {

            //没用优惠券扣余额
            $user_db = M('app_users');
            $user_balance = $user_db->where('user_id=' . $uid)->field('purse_balance')->find();
            //抱歉余额不足
            if (!$real_amount || !$user_balance['purse_balance'] || $real_amount > $user_balance['purse_balance'])
                return RET_NO_V(400, '抱歉余额不足');
            //用户钱包处理 db_user_purse
            $user_purse_db = M('user_purse');
            $purse_data = array(
                'user_id' => $uid,
                'purse_amount' => $real_amount,
                'purse_type' => 2,//订单消费
                'change_time' => date('Y-m-d H-i-s', time()),
                'change_remark' => $change_remark,
                'order_id' => $order_id,
                'sum_amount'=>get_user_balance($uid) - $real_amount
            );
            //新增用户钱包明细
            $purse_adret = $user_purse_db->add($purse_data);
            //计算用户最终剩余多少余额
            $balance = $user_balance['purse_balance'] - $real_amount;
            //更新用户余额
            $user_upret = $user_db->where('user_id=' . $uid)->setField('purse_balance', $balance);
            if (!$user_upret||!$purse_adret){
                $order_db->rollback();
                $order_pay->where(array('order_id' => $order_id))->save(array('pay_time' => date('Y-m-d H-i-s', time()), 'status' => 2));
                return RET_NO_V(400, '抱歉，用户钱包支付失败！');
            }
        }

        $data = array('pay_time' => date('Y-m-d H-i-s', time())
        , 'voucher_no' => $out_trade_no
        , 'pay_account' => getUserMobileForType($uid, 1)//支付的是手机号
        , 'status' => 1);
        //更改订单支付状态
        $ret = $order_pay->where(array('order_id' => $order_id))->save($data);

        $resmsm_ret = M('order_resmsm')->where(array('order_id' => $order_id))->save(array('status' => 1, 'pay_status' => 1));//订单中间表状态修改

        if (!$ret || !$resmsm_ret) {
            $order_db->rollback();
            return RET_NO_V(400, '订单支付信息有误');
        }

        //更改订单表支付状态
        $retss = $order_db->where(array('order_id' => $order_id))->save(array('pay_status' => 1, 'status' => 1));

        if (!$retss) {
            $order_db->rollback();
            return RET_NO_V(400, '订单支付信息有误');
        } else {
            $order_db->commit();
            return RET_NO_V(200, '订单余额支付成功');
        }

    }

    /**
     * @api {get} recommedCountAmount/token/:token/uid/:uid/utype/:utype 获取推荐的人数和持续奖励金额
     * @apiGroup common
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiParam {Int} utype 用户类别1：普通用户，2：跑客 .必填
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     * {
     * "retCode": 200,
     * "retDesc": "获取数据成功",
     * "retValue": {
     *          "user_id": "61",
     *          "recommend_person_count": "1", //推荐的总人数
     *           "recommend_amount": "5.00" //获得的推荐奖励金额
     *          "recom_pn_count": "0",//推荐的跑客人数
     *          "recom_user_count": "0",//推荐的用户人数
     *          "recommend_relation_count": 0//推荐的关系用户人数(指一级的用户推荐二级的用户的数量 + 二级的用户推荐的三级用户的数量)
     *           "rate"://百分比
     *            "ranking"//排名
     *      }
     * }
     **/
    function recommedCountAmount()
    {
        $uid = I('uid');
        $utype = I('utype');

        if (!$utype)
            return RET_NO_V(400, '参数为空');

        if ($utype == '1') {
            verificationToken();
            $user_db = M('app_users');
            $user_obj = $user_db->where('user_id = ' . $uid)->field('user_id,recommend_person_count,recommend_amount')->find();//推荐的总数，和 推荐总金额
//            dump($user_db->getLastSql());
            if (!$user_obj)
                return RET_NO_V(400, '获取数据失败');
        }
        if ($utype == '2') {
            pnerificationToken();
            $user_db = M('dispatch');
            $user_obj = $user_db->where('dispatch_id = ' . $uid)->field('dispatch_id,recommend_person_count,recommend_amount')->find();

            if (!$user_obj)
                return RET_NO_V(400, '获取数据失败');
        }

        //推荐的跑客数量
        $recommend_db = M('recommend r1');//推荐人表
        $recom_pn_count = $recommend_db->where(array('recom_person_id' => $uid, 'recom_person_type' => $utype, 'recommended_person_type' => 2))->count();//获取uid推荐跑客记录数
        $recom_user_count = $recommend_db->where(array('recom_person_id' => $uid, 'recom_person_type' => $utype, 'recommended_person_type' => 1))->count();//获取uid推荐用户记录数
        $user_obj['recom_pn_count'] = $recom_pn_count;
        $user_obj['recom_user_count'] = $recom_user_count;
//        dump('推荐的一级跑客记录数');
//        dump($recommend_db->getLastSql());
//        dump($recom_pn_count);
//        dump('推荐的一级用户记录数');
//        dump($recom_user_count);
//        dump('获取uid推荐人的一级用户：');

        //一级跑客和用户推荐的用户记录数（包括一级的跑客和用户）
        $recommend_pn_two_three_totalcount = $recommend_db->join(' left join db_recommend r2 on r1.recommended_person_id = r2.recom_person_id and r1.recommended_person_type = r2.recom_person_type')
            ->join(' left join db_recommend r3 on r2.recommended_person_id = r3.recom_person_id and r2.recommended_person_type = r3.recom_person_type')
            ->where(' r1.recom_person_id=' . $uid . ' and r1.recom_person_type=' . $utype .
                ' and r2.recommended_person_id is not null' .
                ' and( CASE when r3.recommended_person_id is null then r2.recommended_person_type=1 end' .
                ' or case when r3.recommended_person_id is not null then r3.recommended_person_type=1 end
                                                         or case when r2.recommended_person_id is not null and r3.recommended_person_id is not null and r3.recommended_person_type=2 then r2.recommended_person_type=1 end )')
//下面是三级推荐的用户总数
//                                                                ' and( CASE when r2.recommended_person_id is null then r1.recommended_person_type=1 end
//                                                                or case when r2.recommended_person_id is not null and r3.recommended_person_id is null then r2.recommended_person_type=1 end
//                                                                or case when r2.recommended_person_id is not null and r3.recommended_person_id is not null then r3.recommended_person_type=1 end
//                                                                or case when r2.recommended_person_id is not null and r3.recommended_person_id is not null and r3.recommended_person_type=2 then r2.recommended_person_type=1 end                                                           )')
            ->count();
//        dump('二级推荐用户总数：');
//        dump($recommend_db->getLastSql());
//        dump($recommend_pn_two_three_totalcount);

        $user_obj['recommend_relation_count'] = $recommend_pn_two_three_totalcount;
//        dump('获取uid推荐的关系户的总数：');
//        dump($user_obj['recommend_relation_count']);

        $sql = "select src1.recom_person_id,src1.recom_person_type,src1.rownum as ranking,src1.count,src1.rownum,FORMAT(((src1.total-src1.rownum)/src1.total)*100,2) as rate" .
            " from (" .
            " select src.recom_person_id,src.recom_person_type,src.count" .
            ",CASE WHEN @rowtotal = src.count THEN @rownum" .
            " WHEN @rowtotal := src.count THEN @rownum :=@rownum + 1" .
            " WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1" .
            " END AS rownum" .
            " ,total" .
            " from (" .
            "  select r.recom_person_id,r.recom_person_type" .
            "  ,count(r.recommended_person_id) as count " .
            "  from db_recommend r" .
            " left join db_dispatch d on d.dispatch_id = r.recom_person_id and r.recom_person_type = 2" .
            " where r.recommended_person_type = 1  and ( case when d.dispatch_id is not null then d.account_status != 2 else '1' end)" .
            "  GROUP BY r.recom_person_id,r.recom_person_type" .
            "  order by count desc " .
            " ) as src," .
            " (SELECT @rownum := 0 ,@rowtotal := NULL) r,(select count(*) as total from db_recommend)t) as src1" .
            " where src1.recom_person_id = " . $uid . " and src1.recom_person_type=" . $utype;
        $ranking_obj = M()->query($sql);
//        dump(M()->getLastSql());
        if ($ranking_obj) {
            $user_obj['rate'] = $ranking_obj[0]['rate'];//百分比
            $user_obj['ranking'] = $ranking_obj[0]['ranking'];//排名
        } else {
            $user_obj['rate'] = '0.00';//百分比
            $user_obj['ranking'] = '0';//排名
        }
//        dump($user_obj);
        if ($user_obj) {
            return RET(200, '获取数据成功', $user_obj);
        } else {
            return RET_NO_V(400, '获取数据失败');
        }

    }

    /**
     * @api {get} getNewMsgCount/token/:token/uid/:uid/utype/:utype 获取新消息记录数
     * @apiGroup common
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiParam {Int} utype 用户类别1：普通用户，2：跑客 .必填
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     * {
     * "retCode": 200,
     * "retDesc": "获取新消息记录数成功",
     * "retValue": "3"
     * }
     **/
    function getNewMsgCount()
    {

        $uid = I('uid');
        $utype = I('utype');
        if (!$utype)
            return RET_NO_V(401, '参数有误');
        $msg_count = 0;
        if ($utype == 1) {
            verificationToken();
            $dismsg_db = M('user_message us');
            $msg_count = $dismsg_db->where('user_id=' . $uid . ' and is_read = 0 ')
                ->count();
        }
        if ($utype == 2) {
            pnerificationToken();
            $dismsg_db = M('disptch_message ds');
            $msg_count = $dismsg_db->where('dispatch_id=' . $uid . ' and is_read = 0 ')
                ->count();
        }

        if ($msg_count)
            return RET(200, '获取新消息记录数成功', $msg_count);
        else
            return RET_NO_V(400, '获取新消息记录数有误');
    }

    /**
     * @api {get} getMessages/token/:token/uid/:uid/utype/:utype/page/:page/pagenum/:pagenum 获取系统消息集合
     * @apiGroup common
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiParam {Int} utype 用户类别1：普通用户，2：跑客 .必填
     * @apiParam {Int} page 第几页  默认1 选填
     * @apiParam {Int} pagenum 每页的记录数.默认10 选填
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     * {
     * "retCode": 200,
     * "retDesc": "获取数据成功",
     *   "retValue":   {
     * "data": [
     *           {
     *           "user_msg_id": "1",
     *           "user_id": "97",
     *           "message_id": "1",
     *           "is_read": "0"
     *           }
     *           ],
     *   "count": 0
     * },
     * {
     * "retCode": 200,
     * "retDesc": "获取数据成功",
     *   "retValue": {
     *  "data": [
     *   {
     *   "dispatch_msg_id": "12",
     *   "dispatch_id": "102",
     *   "message_id": null,
     *   "is_read": "0",
     *   "title": "跑客资料审核情况通知",
     *   "intro": "恭喜您，您提交的申请资料已经通过了审核！您可以来公司参加培训了！",
     *   "content": "恭喜您，您提交的申请资料已经通过了审核！您可以来公司参加培训了！",
     *   "time": "2016-10-08 11:05:39"
     *   }
     *  ],
     *  "count": 0
     * }
     **/
    function getMessages()
    {
//

        $uid = I('uid');
        $utype = I('utype');
        $page = I("page") == null ? 1 : I("page");
        $pagenum = I("pagenum") == null ? 10 : I("pagenum");
        if (!$utype)
            return RET_NO_V(400, '参数有误');

        $rets = array();
        if ($utype == 1) {
            verificationToken();
            $dismsg_db = M('user_message');
            $count = $dismsg_db->where('user_id=' . $uid)->count();
            $dismsgs = $dismsg_db->where('user_id=' . $uid)->limit(($page - 1) * $pagenum, $pagenum)->order('time desc')->select();
            $dismsg_db->where('user_id=' . $uid)->save(array('is_read' => 1));

            $rets['data'] = $dismsgs;
            $rets['count'] = ceil($count / $pagenum);
        }
        if ($utype == 2) {
            pnerificationToken();
            $dismsg_db = M('disptch_message');
            $count = $dismsg_db->where('dispatch_id=' . $uid)->count();
            $dismsgs = $dismsg_db->where('dispatch_id=' . $uid)->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->order('time desc')->select();
            $dismsg_db->where('dispatch_id=' . $uid)->save(array('is_read' => 1));
            $rets['data'] = $dismsgs;
            $rets['count'] = ceil($count / I("pagenum"));
        }

        if ($dismsgs)
            return RET(200, '获取新消息成功', $rets);
        else
            return RET_NO_V(400, '获取新消息有误');
    }

    /**
     * @api {get} getMsgContent/token/:token/uid/:uid/utype/:utype/msg_id/:msg_id 获取消息内容
     * @apiGroup common
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiParam {Int} utype 用户类别1：普通用户，2：跑客 .必填
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     * {
     * "retCode": 200,
     * "retDesc": "获取数据成功",
     * "retValue": {
     *                "dispatch_msg_id": "12",
     *               "dispatch_id": "102",
     *               "message_id": null,
     *               "is_read": "0",
     *               "title": null,
     *               "intro": null,
     *               "content": null,
     *               "time": "2016-10-08 11:05:39",
     *               "message_type": null,
     *               "is_top": null,
     *               "send_time": null,
     *               "validate_time": null
     *      }
     * },
     * {
     * "retCode": 200,
     * "retDesc": "获取数据成功",
     * "retValue": {
     *           "user_msg_id": "1",
     *           "user_id": "97",
     *           "message_id": "1",
     *           "is_read": "0",
     *           "message_type": "1",
     *           "title": "\u7269\u54c1\u4fdd\u4ef7\u901a\u77e5",
     *           "content": "\u4eb2\u7231\u7684\u5e2e\u8fbe\u5bb6\u4eba\u4eec\uff0c\u60a8\u597d\uff0c\u611f\u8c22\u60a8\u5bf9\u5e2e\u8fbe\u8dd1\u817f\u5e73\u53f0\u7684\u4e00\u76f4\u4ee5\u6765\u7684\u539a\u7231\uff0c\u4e3a\u4e86\u63d0\u5347\u7528\u6237\u4f53\u9a8c\uff0c\u6211\u4eec\u63a8\u51fa\u7269\u54c1\u4fdd\u4ef7\u529f\u80fd",
     *           "intro": "\u4eb2\u7231\u7684\u5e2e\u8fbe\u5bb6\u4eba\u4eec\uff0c\u60a8\u597d\uff0c\u611f\u8c22\u60a8\u5bf9\u5e2e\u8fbe\u8dd1\u817f\u5e73\u53f0\u7684\u4e00\u76f4\u4ee5\u6765\u7684\u539a\u7231\uff0c\u4e3a\u4e86\u63d0\u5347\u7528\u6237\u4f53\u9a8c\uff0c\u6211\u4eec\u63a8\u51fa\u7269\u54c1\u4fdd\u4ef7\u529f\u80fd",
     *           "is_top": "1",
     *           "send_time": "2016-06-28 15:28:47",
     *           "validate_time": "2016-06-28 15:28:47"
     *           }
     * }
     **/
    function getMsgContent()
    {
        $msg_id = I('msg_id');
        $utype = I('utype');
        if (!$utype)
            return RET_NO_V(400, '参数有误');
        $dismsgs = array();
        if ($utype == 1) {
            verificationToken();
            $dismsg_db = M('user_message us');
            $dismsgs = $dismsg_db->where('user_msg_id=' . $msg_id)->find();
        }
        if ($utype == 2) {
            pnerificationToken();
            $dismsg_db = M('disptch_message ds');
            $dismsgs = $dismsg_db->where('dispatch_msg_id=' . $msg_id)->find();
        }

        if ($dismsgs)
            return RET(200, '获取消息内容成功', $dismsgs);
        else
            return RET_NO_V(400, '获取消息内容有误');
    }

    /**
     * @api {get} changeMsgReadStatus/token/:token/uid/:uid/utype/:utype/ 修改用户消息为“已读”
     * @apiName 用户消息中心
     * @apiGroup common
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} utype 用户类型，1：普通用户，2：跑客.
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     * {
     * "retCode": 200,
     * "retDesc": "设置为已读的数据成功",
     * "retValue": ""
     * }
     **/
    function changeMsgReadStatus()
    {
        $utype = I('utype');
        $uid = I('uid');
        if (!$utype)
            return RET_NO_V(400, '参数有误');
        $dismsgs = "";
        if ($utype == 1) {
            verificationToken();
            $usermsg_db = M('user_message us');
            $dismsgs = $usermsg_db->field("GROUP_CONCAT(user_msg_id) as msg_id")->where('user_id=' . $uid . ' and is_read=0')->select();
        }
        if ($utype == 2) {
            pnerificationToken();
            $dismsg_db = M('disptch_message ds');
            $dismsgs = $dismsg_db->field("GROUP_CONCAT(dispatch_msg_id) as msg_id")->where('dispatch_id=' . $uid . ' and is_read=0')->select();
        }

        if (!$dismsgs || !$dismsgs[0]['msg_id'])
            return RET_NO_V(200, '无需要设置为已读的数据');

        $msg_ids = rtrim($dismsgs[0]['msg_id'], ",");
        if ($utype == 1) {
            $user_ret = $usermsg_db->where('user_msg_id in(' . $msg_ids . ')')->setField('is_read', 1);
            if (!$user_ret)
                return RET_NO_V(400, '设置' . $msg_ids . '为已读的数据失败');
            else
                return RET_NO_V(200, '设置为已读的数据成功');
        }
        if ($utype == 2) {
            $dis_ret = $dismsg_db->where('dispatch_msg_id in(' . $msg_ids . ')')->setField('is_read', 1);
            if (!$dis_ret)
                return RET_NO_V(400, '设置' . $msg_ids . '为已读的数据失败');
            else
                return RET_NO_V(200, '设置为已读的数据成功');
        }
    }

    /**
     * @api {get} changeUserSex/token/:token/uid/:uid/sex/:sex/region/:region/ 修改用户性别
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {Int} sex 性别. 必填 0 保密 1 男 2 女
     * @apiParam {String} region 地区.
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * */
    function changeUserSex()
    {
        //verificationToken();
        $app_users = M('app_users');
        $sex = I('sex');
        $region = I('region');
        $ret = 0;
        if ($region) {
            $ret = $app_users->where(array('user_id' => I('uid')))->save(array('region' => $region));
        } else {
            $ret = $app_users->where(array('user_id' => I('uid')))->save(array('sex' => $sex));
        }
        if ($ret) {
            return RET_NO_V(1, "有修改");
        } else {
            return RET_NO_V(0, "无修改");
        }
    }

    /**
     * @api {get} getPnOrderList/token/:token/uid/:uid/ 跑客获取跑腿成功订单
     * @apiGroup pn
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *  {
     *      "retCode": 200,
     *      "retDesc": "获取订单成功",
     *      "retValue":{
     *          "data": [
     *          {
     *              "order_number": "BN20161007065657739442",           //订单号
     *              "order_type": "1",                                  //订单类型:1取送东西，2代买，3排队
     *              "send_address": "河南省国家大学科技园东区-18号楼",     //发件人地址
     *              "reci_address": "25中家属院",                       //收件人地址
     *              "balance_amount": "11.68",                          //金额
     *              "order_id":102
     *          }
     *               ],"count":0}
     *  }
     **/
    function getPnOrderList()
    {
        pnerificationToken();
        $order = M("order");
        $count = $order->where(array('dispatch_id' => I('uid'), 'status' => 7))->count();
        $ret = $order->where(array('dispatch_id' => I('uid'), 'status' => 7))->field('order_number,send_address_floor,reci_address_floor,order_type,send_address,order_time,dispatch_get_money,disp_eval_value,reci_address,order_id,order_amount,queue_address')->order('order_id desc')->limit((I("page") - 1) * I("pagenum"), I("pagenum"))->select();
        $rets['data'] = $ret;
        $rets['count'] = ceil($count / I("pagenum"));

        if ($ret) {
            return RET(200, '获取订单成功', $rets);
        } else {
            return RET_NO_V(400, '抱歉订单为空');
        }
    }

    /**
     * @api {get} getPnEarnRanking/token/:token/uid/:uid 跑客今日赚取金额排行榜
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *  {
     *      "retCode": 200,
     *      "retDesc": "获取跑客今日赚取金额排行榜",
     *      "retValue": [
     *          {
     *              "balance_amount": "14.40",           //今日赚取金额
     *              "dispatch_name": "张三",
     *          }
     *               ]
     *  }
     **/
    function getPnEarnRanking()
    {
        pnerificationToken();
        $order = M("dispatch_balance b");
        $ret = $order->field('sum(b.balance_amount) as  balance_amount,d.dispatch_name')
            ->join('join db_dispatch d on d.dispatch_id = b.dispatch_id')
            ->where("b.balance_type in(1,3,5) and DATE_FORMAT(b.time,'%Y-%m-%d') = DATE_FORMAT(now(),'%Y-%m-%d')"
                . " and d.is_sign=2 and account_status=1")
            ->group('d.dispatch_name')
            ->order('balance_amount desc,d.dispatch_name')
            ->limit(0, 10)
            ->select();

        if ($ret) {
            return RET(200, '获取跑客今日赚取金额排行榜', $ret);
        } else {
            return RET_NO_V(400, '抱歉跑客今日赚取金额排行榜为空');
        }
    }

    /**
     * @api {get} getPnRobOrderRanking/token/:token/uid/:uid 跑客今日接单量排行榜
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *  {
     *      "retCode": 200,
     *      "retDesc": "获取跑客今日接单量排行榜",
     *      "retValue": [
     *          {
     *              "balance_amount": "14.40",           //今日赚取金额
     *              "dispatch_name": "张三",
     *          }
     *               ]
     *  }
     **/
    function getPnRobOrderRanking()
    {
        pnerificationToken();
        $order = M("order o");
        $ret = $order->field('d.dispatch_name,count(o.order_id) as  counts')
            ->join('db_dispatch d on d.dispatch_id = o.dispatch_id')
//            ->where("o.status=7 and o.pay_status=1 and DATE_FORMAT(order_time,'%Y-%m-%d') >='".I("start_date")."'".
//                " and DATE_FORMAT(order_time,'%Y-%m-%d') <= DATE_FORMAT(now(),'%Y-%m-%d')")
            ->where("o.status=7 and o.pay_status=1 and DATE_FORMAT(order_time,'%Y-%m-%d') = DATE_FORMAT(now(),'%Y-%m-%d')")
            ->group('d.dispatch_name ')
            ->order('counts desc,d.dispatch_name')
            ->limit(0, 10)
            ->select();

        if ($ret) {
            return RET(200, '获取跑客今日接单量排行榜', $ret);
        } else {
            return RET_NO_V(400, '抱歉跑客今日接单量排行榜为空');
        }
    }

    /**
     * @api {get} getPnEvalStartRanking/token/:token/uid/:uid/ 跑客今日接单量排行榜
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *  {
     *      "retCode": 200,
     *      "retDesc": "获取跑客今日好评排行榜",
     *      "retValue": [
     *          {
     *              "dispatch_name": "张三",           //跑客姓名
     *              "eval_value": "5"                  //今日星星总数
     *          }
     *          {
     *              "dispatch_name": "李四",
     *              "eval_value": "5"
     *          }
     *               ]
     *  }
     **/
    function getPnEvalStartRanking()
    {
        pnerificationToken();
        $order = M("order o");
        $ret = $order->field('d.dispatch_name,sum(o.user_eval_value) as  eval_value')
            ->join('db_dispatch d on d.dispatch_id = o.dispatch_id')
            ->where("o.status=7 and o.pay_status=1 and DATE_FORMAT(order_time,'%Y-%m-%d') = DATE_FORMAT(now(),'%Y-%m-%d')")
            ->group('d.dispatch_name ')
            ->order('eval_value desc,d.dispatch_name')
            ->limit(0, 10)
            ->select();

        if ($ret) {
            return RET(200, '获取跑客今日好评排行榜', $ret);
        } else {
            return RET_NO_V(400, '抱歉跑客今日好评排行榜为空');
        }
    }

    /**
     * @api {get} orderRepeat/token/:token/uid/:uid/order_id/:order_id 订单重发
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiParam {Int} order_id 订单id. 必填
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *  {
     *      "retCode": 200,
     *      "retDesc": "重发成功",
     *      "retValue": [
     *          {
     *               "uid": "2",
     *              "token": "e683b31ea6c7a532574b20b53e7b34e9",
     *              "order_type": 3,
     *              "city_id": 128,
     *              "res_type": "餐厅",
     *              "remark": "",
     *              "queue_address": "河南省国家大学科技园东区创新园1号-A座",
     *              "replace_mobile": "13137154660",
     *              "coupon_id": "2",
     *              "company_id": 1,
     *              "is_reservation": 0,
     *              "queue_time": "2016-10-25 9:32:27",
     *              "hour_long": "30",
     *              "voucher_no": "WKTRADENO201692593240762437",
     *              "pay_method": 1,
     *              "order_amount": "12.00",
     *              "real_amount": "4.00",
     *              "reci_address": "0",
     *              "reci_latit": 113.6072,
     *              "reci_longit": 34.80251,
     *              "reci_mobile": "0",
     *              "reci_address_floor": "0",
     *              "send_address_floor": "",
     *              "send_latit": 34.8038,
     *              "send_longit": 113.6086,
     *              "user_id": 2,
     *              "order_id": 1,
     *              "conveyance_id": 0,
     *              "is_have_price": 0
     *          }
     *               ]
     *  }
     **/
    function orderRepeat()
    {
        verificationToken();
        $order = M('order_resmsm r');
        $resms = $order->field('order_data')
            ->join('db_order o on o.order_id=r.order_id')
            ->where(array('r.order_id' => I('order_id'), 'status' => 1, 'is_send' => 0))->find();
//        dump($resms);
//        dump($order->getLastSql());
        if ($resms && $resms['order_data']) {
            $resms_arr = json_decode($resms['order_data'], true);
            $appoints = $resms_arr;
            $appoints['city_id'] = intval($resms_arr['city_id']);
            $appoints['order_type'] = intval($resms_arr['order_type']);
            $appoints['order_id'] = intval($resms_arr['order_id']);
            $appoints['conveyance_id'] = intval($resms_arr['conveyance_id']);
            $appoints['company_id'] = intval($resms_arr['company_id']);
            $appoints['user_id'] = intval($resms_arr['user_id']);
            $appoints['pay_method'] = intval($resms_arr['pay_method']);
            $appoints['send_longit'] = doubleval($resms_arr['send_longit']);
            $appoints['send_latit'] = doubleval($resms_arr['send_latit']);
            $appoints['reci_latit'] = doubleval($resms_arr['reci_latit']);
            $appoints['reci_longit'] = doubleval($resms_arr['reci_longit']);
            $appoints['is_reservation'] = intval($resms_arr['is_reservation']);
            $appoints['is_have_price'] = intval($resms_arr['is_have_price']);
            $appoints['coupon_id'] = intval($resms_arr['coupon_id']);
            $appoints['hour_long'] = intval($resms_arr['hour_long']);

//            dump(json_encode($appoints));
            $json_ret = json_encode($appoints);
//            push_server_appdata(json_encode($appoints));
            return RET(200, '重发成功', $json_ret);
        } else
            return RET_NO_V(200, '无需要重发的订单');
    }

    /**
     * @api pnQuitBnpt/token/:token/uid/:uid/ 退出帮你跑腿
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *  {
     *      "retCode": 200,
     *      "retDesc": "清除位置成功"
     *      "retValue": ''
     *  }
     **/
    function pnQuitBnpt()
    {
        pnerificationToken();
        $uid = I('uid');
        $token = I('token');
        $dispatch_db = M('dispatch');
        $save_ret = $dispatch_db->where(array('dispatch_id' => $uid, 'token' => $token))->save(array('longitude' => '', 'latitude' => '', 'work_status' => '0'));
        if ($save_ret) {
            return RET_NO_V(200, '清除位置成功');
        } else {
            return RET_NO_V(400, '清除位置失败');
        }
    }

    function testRecommed()
    {

        //verificationToken();
        $order_amounts = get_order_money($_GET['send_latit'], $_GET['send_longit'], $_GET['reci_latit'], $_GET['reci_longit'], $_GET['city_id']);//计算跑腿费=距离跑腿费+夜间加价+临时加价
        dump($order_amounts);
        $order_amount_cal = $order_amounts['totalPrice'];
        dump($_GET);
        dump('1 amount = ' . $order_amount_cal);

        $up_server = trim(I('up_server'));//1|2|3|4|5  服务升级： 加急|保险|是否保温配送|是否易碎|是否贵重
        if ($up_server) {
            $up_server_arr = explode("|", $up_server);
            foreach ($up_server_arr as $value) {
                if ($value == 1) {
                    $_GET['is_insured'] = 1;
                    $_GET['insured_amount'] = 5;//加急费用
                    $order_amount_cal = $order_amount_cal + 5;//计算跑腿费　＋=　加急费用
                }
                if ($value == 2) {
                    $_GET['is_insurance'] = 1;
                    $_GET['insurance_amount'] = 5;//保险费用
                    $order_amount_cal = $order_amount_cal + 5;//计算跑腿费 +=　保险费用
                }

                if ($value == 3)
                    $_GET['is_incubator'] = 1;
                if ($value == 4)
                    $_GET['is_fragile'] = 1;
                if ($value == 5)
                    $_GET['is_valuables'] = 1;
            }
        }
        dump('2 amount = ' . $order_amount_cal);

        if (!$_GET['is_reservation'])
            unset($_GET['reservation_time']);

        if ($_GET['fee'])
            $order_amount_cal = $order_amount_cal + $_GET['fee'];//计算跑腿费 += 小费
        dump('3 amount = ' . $order_amount_cal);

        if ($_GET['is_have_price'])
            $order_amount_cal = $order_amount_cal + $_GET['help_goods_amount'];//计算跑腿费 += 代买商品金额
        dump('4 amount = ' . $order_amount_cal);
        if ($order_amount_cal != $_GET['order_amount'])//前台计算的订单金额 ！= 后台计算的金额
            return RET_NO_V(400, '订单金额计算有误，请重新下单');


        exit;
    }

    function testInsurance()
    {
//        new Model();
        $ret = returnSquarePoint(34.80254805987807, 113.60778155547179, 5);
        dump($ret);
    }

    function testArrayToXml()
    {
//        <xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>
        $xml_arr = array('return_code' => 'SUCCESS', 'return_msg' => 'OK');
        $xml = arrayToXml($xml_arr);
        dump($xml);
    }

    /**
     * @api pnOrderQuery/token/:token/uid/:uid/lat/:/lat/lng/:lng 跑客订单查询
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiParam {Int} lat 维度
     * @apiParam {Int} lng 经度
     **/
    function pnOrderQuery()
    {
        //鉴权
        pnerificationToken();
        $pk_lat = I('lat');
        $pk_lng = I('lng');
        $dispatch = M("dispatch");
        $dispatch_data = $dispatch->where(array('dispatch_id' => I('uid')))->field('order_model,work_status,conveyance_id,dispatch_level_id,company_id,conveyance_id')->find();
        //筛选出没有听单的
        if ($dispatch_data['work_status'] == 1) {
            $get_tc = (100 - (int)getPnIncomeForDispatchId(I('uid'))) * 0.01;
            //dump($get_tc);
            $order_resmsm = M("order_resmsm");
            //查询已经支付过的订单
            $order_data = $order_resmsm->where(array('pay_status' => 1, 'status' => 1))->select();
            //dump($order_data);
            //dump($dispatch_data['order_model']);
            //exit;
            $ret_data = array();
            for ($i = 0; $i < count($order_data); $i++) {
                $data = getDistanceBetweenPointsNew($order_data[$i]['order_lat'], $order_data[$i]['order_lng'], $pk_lat, $pk_lng);
                //dump($data);
                if ((int)$data['kilometers'] <= (int)$dispatch_data['order_model']) {
                    $order_ret = json_decode($order_data[$i]['order_data'], true);
                    //dump($dispatch_data['conveyance_id']);
                    //dump($order_ret['conveyance_id']);
                    //筛选出相关团体
                    if ($dispatch_data['company_id'] == $order_ret['company_id'] || $order_ret['company_id'] == 1) {
                        //筛选出相关运输工具
                        if ($dispatch_data['conveyance_id'] == $order_ret['conveyance_id']) {
                            $order_ret['distance'] = round($data['kilometers'], 2);
                            //$order_ret['get_money'] = (string)round($order_ret['order_amount']*$get_tc,2);
                            $order_ret['get_money'] = $order_ret['order_amount'];
                            $order_ret['conveyance'] = conveyance($order_ret['conveyance_id']);
                            $ret_data[] = $order_ret;
                        }
                    }
                }
            }
            if (count($ret_data)) {
                return RET(200, "ok", $ret_data);
            } else {
                return RET_NO_V(401, "暂无订单");
            }
        } else {
            return RET_NO_V(400, "没有开工");
        }

    }

    /**
     * @api updatePnActive/token/:token/uid/:uid/is_background/:is_background 跑客是否在后台
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiParam {String} is_background 是否在后台1在后台2挂起
     **/
    function updatePnActive()
    {
        pnerificationToken();
        $dispatch_id = I('uid');

        $is_background = I('is_background');

        $dispatch_obj = M('dispatch')->where(array('dispatch_id' => $dispatch_id,
//            'is_sign'=>2,
            'account_status' => 1, 'work_status' => 1))->field('latitude,longitude,jpush_id,place_up_time')->find();
        $dis_active_db = M('dispatch_active');
        if ($dispatch_obj) {
            if ($is_background == '2') {//后台转到前台
                //$count_ret = count_background_time($dispatch_id);
                $active_ret = $dis_active_db->where('dispatch_id=' . $dispatch_id)->delete();
                $upmsg_ret = login_upmsg_sys($dispatch_id, 2);//更新用户系统消息 信息

                if ($active_ret && $upmsg_ret)
                    RET_NO_V(200, '活跃跑客信息删除成功');
                else
                    RET_NO_V(400, '活跃跑客信息删除失败');
            } elseif ($is_background == '1') {//前台转到后台
                $data = array('dispatch_id' => $dispatch_id
                , 'latitude' => $dispatch_obj['latitude']
                , 'longitude' => $dispatch_obj['longitude']
                , 'time' => date('Y-m-d H:i:s', time())
                , 'is_background' => $is_background
                , 'jpush_id' => $dispatch_obj['jpush_id']
                , 'place_up_time' => $dispatch_obj['place_up_time']);

                $active_obj = $dis_active_db->where('dispatch_id=' . $dispatch_id)->find();

                if ($active_obj) {
                    $active_ret = $dis_active_db->where('dispatch_id=' . $dispatch_id)->save($data);
                } else
                    $active_ret = $dis_active_db->add($data);

                if ($active_ret)
                    RET_NO_V(200, '活跃跑客信息更新成功');
                else
                    RET_NO_V(400, '活跃跑客信息更新失败');
            }
        } else {
            return RET_NO_V(400, '跑客信息有误');
        }
    }


    /**
     * @api get_push_order/token/:token/uid/:uid/order_id/:order_id 跑客获取极光推送的订单数据
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiParam {String} order_id 订单ID
     **/
    function get_push_order()
    {
        pnerificationToken();
        $order_resmsm = M('order_resmsm');
        $resms = $order_resmsm->where(array('order_id' => I('order_id')))->field('order_data')->find();

        if ($resms && $resms['order_data']) {
            $resms_arr = json_decode($resms['order_data'], true);
            $appoints = $resms_arr;
            $appoints['city_id'] = intval($resms_arr['city_id']);
            $appoints['order_type'] = intval($resms_arr['order_type']);
            $appoints['order_id'] = intval($resms_arr['order_id']);
            $appoints['conveyance_id'] = intval($resms_arr['conveyance_id']);
            $appoints['company_id'] = intval($resms_arr['company_id']);
            $appoints['user_id'] = intval($resms_arr['user_id']);
            $appoints['pay_method'] = intval($resms_arr['pay_method']);
            $appoints['send_longit'] = doubleval($resms_arr['send_longit']);
            $appoints['send_latit'] = doubleval($resms_arr['send_latit']);
            $appoints['reci_latit'] = doubleval($resms_arr['reci_latit']);
            $appoints['reci_longit'] = doubleval($resms_arr['reci_longit']);
            $appoints['is_reservation'] = intval($resms_arr['is_reservation']);
            $appoints['is_have_price'] = intval($resms_arr['is_have_price']);
            $appoints['coupon_id'] = intval($resms_arr['coupon_id']);
            $appoints['hour_long'] = intval($resms_arr['hour_long']);

//            dump(json_encode($appoints));
            $json_ret = json_encode($appoints);
//            push_server_appdata(json_encode($appoints));
            return RET(200, '获取成功', $json_ret);
        } else {
            return RET_NO_V(400, "无此订单");
        }
    }

    /**
     * @api getRankingList/token/:token/uid/:uid/utype/:utype 获取推荐排行榜
     * @apiGroup common
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiParam {String} utype 推荐人类别 1：用户，2跑客
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *  {
     *      "retCode": 200,
     *      "retDesc": "清除位置成功"
     *      "retValue":
     * "raning": [
     *       {
     *          "recom_person_id": "1",   //推荐人id
     *          "counts": "49", //推荐用户数（用户+跑客）
     *          "rownum": "1",//排名
     *          "mobile": "150****8022"  //手机号
     *        },
     *      {
     *         "recom_person_id": "21",
     *         "counts": "10",
     *         "rownum": "2",
     *         "mobile": "150****8032"
     *         }],
     * "myRaning": [
     * {
     *    "recom_person_id": "21",
     *    "counts": "10",
     *    "rownum": "2",
     *    "mobile": "150....8082"
     * } ]
     *  }
     **/
    function getRecommendRankingList()
    {
        $utype = I('utype');
        $uid = I('uid');
//        dump('uid = '.$uid);
//        dump('utype = '.$utype);
        if ($utype == 1) {
            verificationToken();
        } elseif ($utype == 2) {
            pnerificationToken();
        }
        $user_sql = "select  src1.recom_person_id,src1.recom_person_type,src1.counts,INSERT(src1.mobile,4,4,'****') as mobile,rownum" .
            " from(" .
            " select src.*" .
            " ,CASE WHEN @rowtotal = src.counts THEN @rownum" .
            "                    WHEN @rowtotal := src.counts THEN @rownum :=@rownum + 1" .
            "                     WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1" .
            "                      END AS rownum" .

            " from(" .
            " select r.recom_person_id,r.recom_person_type" .
            "		,count(r.recommended_person_id) as counts" .
            " ,case when a.user_id is null then d.mobile " .
            "		      when d.dispatch_id is null then a.mobile end as mobile" .
            " from db_recommend r " .
            " left join db_app_users a on a.user_id = r.recom_person_id and r.recom_person_type=1 " .
            " left join db_dispatch d on d.dispatch_id = r.recom_person_id and r.recom_person_type = 2 " .
            " where r.recommended_person_type = 1 and ( case when d.dispatch_id is not null then d.account_status != 2 else '1' end) " .
            " GROUP BY r.recom_person_id,r.recom_person_type" .
            " order by count(r.recom_person_id) desc)src ,(SELECT @rownum := 0 ,@rowtotal := NULL) r " .
            " )src1 " .
            " where src1.rownum <=10";
//            dump($user_sql);
        $ranking_objs = M()->query($user_sql);
        $data['raning'] = $ranking_objs;


        $sql = "select  src1.recom_person_id,src1.recom_person_type,src1.counts,src1.mobile,src1.rownum  " .
            " from(" .
            " select src.*" .
            ",CASE WHEN @rowtotal = src.counts THEN @rownum" .
            "                    WHEN @rowtotal := src.counts THEN @rownum :=@rownum + 1" .
            "                     WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1" .
            "                      END AS rownum" .

            " from(" .
            " select r.recom_person_id,r.recom_person_type" .
            "		,count(r.recommended_person_id) as counts" .
            ",case when a.user_id is null then d.mobile " .
            "		      when d.dispatch_id is null then a.mobile end as mobile " .
            " from db_recommend r " .
            " left join db_app_users a on a.user_id = r.recom_person_id and r.recom_person_type=1 " .
            " left join db_dispatch d on d.dispatch_id = r.recom_person_id and r.recom_person_type = 2 " .
            " where r.recommended_person_type = 1 and ( case when d.dispatch_id is not null then d.account_status != 2 else '1' end) " .
            " GROUP BY r.recom_person_id,r.recom_person_type" .
            " order by count(r.recom_person_id) desc)src ,(SELECT @rownum := 0 ,@rowtotal := NULL) r " .
            " )src1 " .
            " where src1.recom_person_id = " . $uid . " and src1.recom_person_type=" . $utype;

        $my_ranking_obj = M()->query($sql);
        if ($my_ranking_obj) {
            $data['myRaning'] = $my_ranking_obj[0];//排名
        } else {
            $data['myRaning'] = '0';//排名
        }
//        dump($data);
        if ($data) {
            return RET(200, '获取推荐排行榜成功', $data);
        } else {
            return RET_NO_V(400, "获取推荐排行榜失败");
        }
    }
    /**
     * @api getRankingList/token/:token/uid/:uid/ 获取魅力值排行榜
     * @apiGroup common
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *  {
     *      "retCode": 200,
     *      "retDesc": "获取魅力值排行榜成功"
     *      "retValue":
     *  "raning": [
     *    {
     *    "dispatch_id": "114",  //跑客id
     *    "job_number": "128114", //工号
     *    "dispatch_name": "李师傅", //姓名
     *    "evaluate_star": "15", //星星总数
     *    "rownum": "1"//排名
     *    },
     *    {
     *    "dispatch_id": "37",
     *    "job_number": "12837",
     *    "dispatch_name": "白师傅",
     *    "evaluate_star": "10",
     *    "rownum": "2"
     *    } ],
     *    "myRaning": [
     *    {
     *    "dispatch_id": "21",
     *    "job_number": "12821",
     *    "dispatch_name": "郑伟",
     *    "evaluate_star": "0",
     *    "rownum": "39"
     *    } ]
     *  }
     **/
//    function getEvaluateStarRankingList(){
////        pnerificationToken();
//        $uid = I('uid');
//        $sql = //'select dispatch_id,job_number,dispatch_name,evaluate_star,rownum from ('.
//                        ' select dispatch_id,job_number,dispatch_name,evaluate_star,rownum '.
//                        ' from('.
//                                ' select d.dispatch_id,d.job_number,CONCAT(left(d.dispatch_name,1),\'师傅\') as dispatch_name,d.evaluate_star'.
//                                            ' ,CASE WHEN @rowtotal = d.evaluate_star THEN @rownum'.
//                                            ' WHEN @rowtotal := d.evaluate_star THEN @rownum :=@rownum + 1'.
//                                            ' WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1'.
//                                            ' END AS rownum '.
//                                ' from db_dispatch d '.
//                                ' where d.is_sign=2'.
//                                ' order by d.evaluate_star desc '.
//                                ' )src '.
//                                ' ,(SELECT @rownum := 0 ,@rowtotal := NULL) r '.
////                        ' )src1'.
//                        ' where rownum = 10';
//        dump($sql);
//        $ranking_objs = M()->query($sql);
//
//        dump($ranking_objs);
//        $my_ranking_obj = M()->query('select dispatch_id,job_number,dispatch_name,evaluate_star,rownum from ('.
//                                                ' select src.*'.
//                                                ' from('.
//                                                ' select d.dispatch_id,d.job_number,CONCAT(left(d.dispatch_name,1),\'师傅\') as dispatch_name,d.evaluate_star'.
//                                                ' ,CASE WHEN @rowtotal = d.evaluate_star THEN @rownum'.
//                                                ' WHEN @rowtotal := d.evaluate_star THEN @rownum :=@rownum + 1'.
//                                                ' WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1'.
//                                                ' END AS rownum '.
//                                                ' from db_dispatch d '.
//                                                ' where d.is_sign=2'.
//                                                ' order by d.evaluate_star desc '.
//                                                ' )src '.
//                                                ' ,(SELECT @rownum := 0 ,@rowtotal := NULL) r '.
//                                                ' )src1'.
//                                        ' where src1.dispatch_id = '.$uid);
//        dump($my_ranking_obj);
//        dump(M()->getLastSql());
//        $data['raning']=$ranking_objs;
//        if(!$my_ranking_obj)
//            $data['myRaning']='0';
//        else
//            $data['myRaning']=$my_ranking_obj[0];
//
//        if($data){
//            return RET(200, '获取魅力值排行榜成功', $data);
//        }else{
//            return RET_NO_V(400,"获取魅力值排行榜失败");
//        }
//    }
    function getEvaluateStarRankingList()
    {
        pnerificationToken();
        $uid = I('uid');
        $dispatch_db = M('dispatch d ');

        $ranking_objs = M()->query('select src.dispatch_id,src.job_number,CONCAT(left(src.dispatch_name,1),\'师傅\') as dispatch_name,src.evaluate_star,src.rownum,src.avatar from(' .
            'SELECT d.dispatch_id,d.job_number,d.dispatch_name ,d.evaluate_star,d.avatar' .
            '  ,CASE WHEN @rowtotal = d.evaluate_star THEN @rownum' .
            '               WHEN @rowtotal := d.evaluate_star THEN @rownum :=@rownum + 1' .
            '                   WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1' .
            '                               END AS rownum' .
            '               FROM db_dispatch d ,(SELECT @rownum := 0 ,@rowtotal := NULL) r' .
            '                where d.is_sign=2  and d.account_status!=2' .
            '                ORDER BY d.evaluate_star desc ' .
            '                               ) as src' .
            '                              where rownum <=10 ');

        $my_ranking_obj = M()->query('select src.dispatch_id,src.job_number,src.dispatch_name,src.evaluate_star,src.rownum,src.avatar from(' .
            'SELECT d.dispatch_id,d.job_number,d.dispatch_name ,d.evaluate_star,d.avatar' .
            '  ,CASE WHEN @rowtotal = d.evaluate_star THEN @rownum' .
            '               WHEN @rowtotal := d.evaluate_star THEN @rownum :=@rownum + 1' .
            '                   WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1' .
            '                               END AS rownum' .
            '               FROM db_dispatch d ,(SELECT @rownum := 0 ,@rowtotal := NULL) r' .
            '                where d.is_sign=2  and d.account_status!=2 ' .
            '                ORDER BY d.evaluate_star desc ' .
            '                               ) as src' .
            '                              where src.dispatch_id = ' . $uid);

        $data['raning'] = $ranking_objs;
        if (!$my_ranking_obj)
            $data['myRaning'] = '0';
        else
            $data['myRaning'] = $my_ranking_obj[0];
        if ($data) {
            return RET(200, '获取魅力值排行榜成功', $data);
        } else {
            return RET_NO_V(400, "获取魅力值排行榜失败");
        }
    }

    /**
     * @api getRankingList/token/:token/uid/:uid/ 获取战力值排行榜
     * @apiGroup common
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *  {
     *      "retCode": 200,
     *      "retDesc": "获取战力值排行榜成功"
     *      "retValue": ''
     *  "raning": [
     *    {
     *    "dispatch_id": "114",  //跑客id
     *    "job_number": "128114", //工号
     *    "dispatch_name": "李师傅", //姓名
     *    "comp_order_num": "15", //完成订单总数
     *    "rownum": "1"//排名
     *    "avatar": "Uploads/pnHeadImg/2016/12/12/20161212092140829815766.jpg"
     *    },
     *    {
     *    "dispatch_id": "521",
     *    "dispatch_name": "钟师傅",
     *    "comp_order_num": "4",
     *    "rownum": "4",
     *    "avatar": "Uploads/pnHeadImg/2016/12/12/20161212092140829815766.jpg"
     *    } ],
     *    "myRaning": [
     *    {
     *    "dispatch_id": "532",
     *    "dispatch_name": "邱珍",
     *    "comp_order_num": "1",
     *    "rownum": "7",
     *    "avatar": "Uploads/pnHeadImg/2016/12/09/201612091515382936717574.jpg"
     *    } ]
     *  }
     **/
    function getFightRankingList()
    {
        pnerificationToken();
        $uid = I('uid');
        $dispatch_db = M('dispatch d ');

        $ranking_objs = $dispatch_db->query(' select src.dispatch_id,src.job_number,CONCAT(left(src.dispatch_name,1),\'师傅\') as dispatch_name,src.comp_order_num,src.rownum,src.avatar from(' .
            ' SELECT d.dispatch_id,d.job_number,d.dispatch_name ,d.comp_order_num,d.avatar' .
            ' ,CASE WHEN @rowtotal = d.comp_order_num THEN @rownum' .
            ' WHEN @rowtotal := d.comp_order_num THEN @rownum :=@rownum + 1' .
            ' WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1' .
            '    END AS rownum' .
            ' FROM db_dispatch d ,(SELECT @rownum := 0 ,@rowtotal := NULL) r' .
            '   where d.is_sign=2 and d.account_status != 2 ' .
            '   ORDER BY d.comp_order_num desc ' .
            '              ) as src' .
            '          where rownum <=10 ');

        $my_ranking_obj = M()->query(' select src.dispatch_id,src.job_number,src.dispatch_name,src.comp_order_num,src.rownum,src.avatar from(' .
            ' SELECT d.dispatch_id,d.job_number,d.dispatch_name ,d.comp_order_num,d.avatar' .
            ' ,CASE WHEN @rowtotal = d.comp_order_num THEN @rownum' .
            ' WHEN @rowtotal := d.comp_order_num THEN @rownum :=@rownum + 1' .
            ' WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1' .
            '    END AS rownum' .
            ' FROM db_dispatch d ,(SELECT @rownum := 0 ,@rowtotal := NULL) r' .
            '   where d.is_sign=2 and d.account_status != 2 ' .
            '   ORDER BY d.comp_order_num desc ' .
            '              ) as src' .
            ' where src.dispatch_id = ' . $uid);

        $data['raning'] = $ranking_objs;
        if (!$my_ranking_obj)
            $data['myRaning'] = '0';
        else
            $data['myRaning'] = $my_ranking_obj[0];

        if ($data) {
            return RET(200, '获取战力值排行榜成功', $data);
        } else {
            return RET_NO_V(400, "获取战力值排行榜失败");
        }
    }

    /**
     * @api getWealthRankingList/token/:token/uid/:uid/ 获取财力值排行榜
     * @apiGroup common
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *  {
     *      "retCode": 200,
     *      "retDesc": "获取财力值排行榜成功"
     *      "retValue": ''
     *  "raning": [
     *    {
     *    "dispatch_id": "114",  //跑客id
     *    "job_number": "128114", //工号
     *    "dispatch_name": "李师傅", //姓名
     *    "total_amount": "15", //完成订单总数
     *    "rownum": "1"//排名
     *    },
     *    {
     *    "dispatch_id": "37",
     *    "job_number": "12837",
     *    "dispatch_name": "白师傅",
     *    "comp_order_num": "10",
     *    "rownum": "2"
     *    } ],
     *    "myRaning": [
     *    {
     *    "dispatch_id": "21",
     *    "job_number": "12821",
     *    "dispatch_name": "郑伟",
     *    "total_amount": "0",
     *    "rownum": "39"
     *    } ]
     *  }
     **/
    function getWealthRankingList()
    {
        pnerificationToken();
        $uid = I('uid');
        $dispatch_db = M('dispatch d ');

        $ranking_objs = M()->query('select * from (select dispatch_id,dispatch_name,job_number,avatar' .
            '  ,total_amount' .
            ' ,CASE WHEN @rowtotal = src.total_amount THEN @rownum' .
            '  WHEN @rowtotal := src.total_amount THEN @rownum :=@rownum + 1' .
            ' WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1' .
            ' END AS rownum ' .
            ' from(' .
            " select b.dispatch_id,d.job_number,CONCAT(left(d.dispatch_name,1),'师傅') as dispatch_name,d.avatar" .
            ' , sum(b.balance_amount) as total_amount ' .
            'from db_dispatch_balance b' .
            ' LEFT JOIN db_dispatch d on d.dispatch_id = b.dispatch_id' .
            ' where  balance_type in(1,3,5) and d.account_status!=2 and d.is_sign = 2 ' .
            ' GROUP BY b.dispatch_id,d.job_number,d.dispatch_name' .
            ' ORDER BY sum(b.balance_amount) desc' .
            ' ) as src,(SELECT @rownum := 0 ,@rowtotal := NULL) r) as src1 where src1.rownum <= 10');
//                                        ,(@i:=@i+1) AS rownum")
//            ->join('(select @i:=0) as it')

        $my_ranking_obj = M()->query('select * from (select src.dispatch_id,dispatch_name,job_number,avatar' .
            '  ,src.total_amount' .
            ' ,CASE WHEN @rowtotal = src.total_amount THEN @rownum' .
            '  WHEN @rowtotal := src.total_amount THEN @rownum :=@rownum + 1' .
            '  WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1' .
            '  END AS rownum ' .
            ' from(' .
            ' select b.dispatch_id,d.job_number,d.dispatch_name,d.avatar' .
            ' , sum(b.balance_amount) as total_amount ' .
            ' from db_dispatch_balance b' .
            ' LEFT JOIN db_dispatch d on d.dispatch_id = b.dispatch_id' .
            ' where  balance_type in(1,3,5) and d.account_status!=2 and d.is_sign = 2 ' .
            ' GROUP BY b.dispatch_id,d.job_number,d.dispatch_name' .
            ' ORDER BY sum(b.balance_amount) desc' .
            ' ) as src,(SELECT @rownum := 0 ,@rowtotal := NULL) r) as src1 where src1.dispatch_id = ' . $uid);

        $data['raning'] = $ranking_objs;
        if (!$my_ranking_obj)
            $data['myRaning'] = '0';
        else
            $data['myRaning'] = $my_ranking_obj[0];

        if ($data) {
            return RET(200, '获取财力值排行榜成功', $data);
        } else {
            return RET_NO_V(400, "获取财力值排行榜失败");
        }
    }

    /**
     * @api change_user_name/token/:token/uid/:uid/user_name/:user_name 更改用户姓名
     * @apiGroup common
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiParam {String} user_name 用户姓名
     */

    function change_user_name()
    {
        verificationToken();
        $app_users = M('app_users');
        $ret = $app_users->where(array('user_id' => I('uid')))->save(array('user_name' => I('user_name')));
        if ($ret) {
            return RET(200, '修改用户姓名成功！', I('user_name'));
        } else {
            return RET_NO_V(400, '抱歉修改用户姓名失败！');
        }
    }


    /**
     * @api change_birth/token/:token/uid/:uid/birth/:birth 更改用户出生年月日
     * @apiGroup common
     * @apiParam {Int} uid 用户唯一ID. 必填
     * @apiParam {String} token 跑腿token,每次登录都会更改. 必填
     * @apiParam {String} birth 用户出生年月日
     */
    function change_birth()
    {
        verificationToken();
        $app_users = M('app_users');
        $ret = $app_users->where(array('user_id' => I('uid')))->save(array('birth' => I('birth')));
        if ($ret) {
            return RET(200, '修改用户出生年月日成功！', I('user_name'));
        } else {
            return RET_NO_V(400, '抱歉，修改用户出生年月日失败！');
        }
    }

    function  testAddPoints()
    {
        $points = array('user_id' => 1, 'points_type' => 1, 'points_value' => 10, 'remark' => '订单积分', 'from_id' => 1);
        dump($points);
        $ret = addPoints($points);
        dump($ret);
    }

    function  testMessageSys()
    {
//        login_upmsg_sys(I('uid'));//参数uid
//        dump(I('message_id'));
//        see_upmsg_sys(I('uid'),I('message_id'));

        return RET(0, "获取消息成功！", see_upmsg_sys(I('uid'), I('message_id')));
//        dump(getmsg_sys_unread(I('uid')));
    }

    /**
     * @api {get} randomCoupon/uid/:uid/token/:token   用户随机获取用户券
     * @apiName 用户随机获取用户券
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *"retCode": 1,
     *"retDesc": "领取成功！",
     *"retValue": {
     *"coupon_type": 1,    //优惠券类型
     *"coupon_value":6 , //优惠券的面值
     *"valid_end_time": 2016-12-19 23:59:59, //优惠券到期时间
     *}
     *}
     * @return 0 表示false   1表示true
     * 12.12之后用
     **/
    function  randomCoupon()
    {
        //第一步 根据userid  和 token 查询出用户的基本信息
        $arr['user_id '] = I('get.uid');
        $arr['token'] = I('get.token');
////     $arr['user_id ']= 685;
////     $arr['token'] ='db70515915d5473fade9e76c84ca6be2';
//       在 'db_app_users'表中看该用户信息
//       $user = M('app_users'); 
//       在 'db_app_users'表中看该用户信息
//       $res=$user->where(array($arr))->select();
//       $res为空则不存在用户信息
//       if(empty($res)){
//          return RET_NO_V(0, "没有这个用户"); 
//       }
        verificationToken();
        //定义优惠劵的coupon_key
        $coupon_key = array('zW74kg8ZU25#C%IW', 'S7Rz6vBSNLLM7nrB', 'B7Rz6VbzHeNy7MrB', 'M8Rz6vBZheNy7NrB', 'jR1sjE4R8G9dMBcB');
        $user_coupon = M('user_coupon');
        //判断该用户是否参加过该活动
        foreach ($coupon_key as $v) {
            $whe['coupon_key'] = $v;
            $whe['user_id'] = $arr['user_id '];
            $result[] = $user_coupon->where($whe)->select();
        }
        foreach ($result as $v) {
            if (!empty($v)) {
                return RET_NO_V(0, "抱歉,您已经参加过本活动了");
            }
        }
        //给第一次参加该活动的用户随机分配一个$coupon_key中的coupon_key
        $user_coupon_key = array_rand($coupon_key, 1);
        $user_coupon_key = $coupon_key["$user_coupon_key"];
        $coupon_info = M('coupon_info');
        //根据$user_coupon_key从coupon_info表中查出该优惠券的信息
        $return = $coupon_info->where(array('coupon_key' => $user_coupon_key))->select();
        //将数组$return变为一位数组
        $return = $return[0];
        //给user_coupon表拼接字段
        $return['valid_end_time'] = coupon_valid_end($user_coupon_key);
        $return['user_id'] = $arr['user_id '];
        $return['is_used'] = 1;
        $return['from_remark'] = 'APP兑换抵扣券，金额为' . $return['coupon_value'] . '元';
        //把此优惠券信息添加到用户user_coupon表中
        //$sql是返回的user_coupon_id
        $sql = $user_coupon->data($return)->add();
        $field = array(
            'coupon_type', 'coupon_value', 'valid_end_time',
        );
        // $user_info = $user_coupon->where($where)->getField('coupon_value,coupon_key,valid_end_time,remark,from_remark');
        //$user_info = $user_coupon->field($field)->where(array('user_coupon_id '=>$sql))->select();
        $user_info = $user_coupon->field($field)->where(array('user_coupon_id ' => array('eq', $sql)))->select();
//            echo $user_coupon->getLastSql();
//            dump($user_info);
        return RET(1, "领取成功", $user_info);
    }

    function  testCount_background_time()
    {
//        login_upmsg_sys(I('uid'));//参数uid
//        dump(I('message_id'));
//        see_upmsg_sys(I('uid'),I('message_id'));

        dump(count_background_time(I('dispatch_id')));
//        dump(getmsg_sys_unread(I('uid')));

//        $totay = round((time()-strtotime(date('Y-m-d').' 01:00:00'))/60);//凌晨到当前时间 的分钟数
//        dump($totay/60);
//        dump(date("Y-m-d",strtotime("-1 day")));
    }

    function test_near_pn()
    {
        //dump(I('lat').','.I('lng'));

        //dump(getPn_nearby(I('lat'),I('lng'),1));

        import("Vendor.Jpush.pnJpushios");
        $jpush = new \pnJpushios();
        $jpush_ret = $jpush->push(array('registration_id' => array('1a1018970aaa88acb40')), '', '您有一个新订单', array('order_id' => 41));
        dump($jpush_ret);
    }

    function  test_order_finish_sms()
    {
        //send_order_finish_sms('13949036223','test00000001');

        // dump(line('34.781178,113.771421','21.669656297030336,110.91838959069625'));

        //早上九点-下午8点的在线时长算法
        //if(strtotime(date('Y-m-d H:i:s'))>=strtotime(date('Y-m-d 09:00:00')) && strtotime(date('Y-m-d H:i:s'))<=strtotime(date('Y-m-d 20:00:00'))){
        //    dump("计时");
        //}
        dump(strtotime(date('Y-m-d H:i:s')));
        dump(strtotime(date('Y-m-d 09:00:00')));
        dump(strtotime(date('Y-m-d 20:00:00')));
    }

    function test_pn_time()
    {
//        ($reservation_objs,$new_reser_time_start,$new_reser_time_end)
        $reser_objs = array(
            array('order_type' => 1,
                'is_reservation' => 1,
                'reservation_time' => '2016-12-20 17:00:00',
                'queue_time' => '',
                'hour_long' => ''),
            array('order_type' => 2,
                'is_reservation' => 1,
                'reservation_time' => '2016-12-19 17:00:00',
                'queue_time' => '',
                'hour_long' => ''),
            array('order_type' => 3,
                'is_reservation' => 1,
                'reservation_time' => '',
                'queue_time' => '2016-12-20 08:00:00',
                'hour_long' => '480'),
            array('order_type' => 3,
                'is_reservation' => 1,
                'reservation_time' => '',
                'queue_time' => '2016-12-19 15:00:00',
                'hour_long' => '90')
        );
        dump($reser_objs);
        dump('新预约单时间：');
        dump(I('start_time'));
        dump(I('end_time'));
        $ret = test_pnrob_reservation($reser_objs, strtotime(I('start_time')), strtotime(I('end_time')));
        dump('是否可以预约结果：');
        dump($ret);
    }

    /**
     * @api {get} orderList/uid/:uid   用户获取自己的订单信息
     * @order_info 用户的dispatch_id
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID.
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *"retCode": 1,
     *"retDesc": "订单信息提示！",
     *"retValue": {
     *"dispatch_id": 85 //派单员id
     *"order_desc" : 您有一个订单正在处理中 //订单描述
     *}
     *}
     * @return 0 表示没有订单信息   1表示有订单信息
     * 12.12之后用
     **/
    function orderDetails()
    {
        //第一步 根据dispatch_id 查询出用户全部订单的基本信息
        $order = M("order");
        $where['user_id'] = I('uid');
        $where['status'][] = array("EGT", 2);
        $where['status'][] = array("LT", 7);
        $order_info["order_id"] = $order->where($where)->getfield('order_id');
        $order_info["order_desc"] = "您有一个订单正在处理中";

        if ($order_info["order_id"]) {
            return RET(1, "数据获取成功", $order_info);
        } else {
            return RET_NO_V(0, "获取数据失败或没有信息");
        }
    }

    /**
     * @api {get} getaddPrice/uid/:uid 获取加价信息
     *
     * @apiGroup pt
     *
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 权限token.
     * @apiParam {Int} cityId 城市ID
     *
     **/
    function getaddPrice()
    {
        $pricing_tactics = M('pricing_tactics');
        $ret = $pricing_tactics->where(array('city_id' => I('cityId')))->field('tactics_array')->find();
        if ($ret['tactics_array']) {
            $tactics_array = json_decode($ret['tactics_array'], TRUE);
            if ("1" != $tactics_array['temporary']['addtimes']) {
                RET(200, "数据获取加价数据成功", $tactics_array['temporary']);
            } else {
                RET_NO_V(400, "无须加价");
            }

        }

    }

    //http://localhost/bnpt/index.php/api/v1/app_market_order_linkman_test/order_id/1
    function dispatch_insurance_test()
    {
        dispatch_insurance(5, 1004, 10);
//        dispatch_insurance_options(9,792,2,6,'','','');
//        app_market_order_linkman(I('order_id'));
//        $order_amount_cal = 7.8;
//        if(I('conveyance_id')==2)
//            $order_amount_cal = $order_amount_cal * 2.5;
//        elseif(I('conveyance_id')==3)
//            $order_amount_cal = $order_amount_cal * 3;
//        dump($order_amount_cal);
    }

    /**
     * @api {get} peripheral/uid/:uid/token/:token/lng/:lng/lat/:lat  根据输入的经纬度查询10个周边
     * @apiName 根据输入的经纬度查询10个周边
     * @apiGroup pt
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Float} lng  经度.
     * @apiParam {Float} lat  纬度.
     * @apiParam {String} url 拼接获取信息的链接地址
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *          "retCode": 0,
     *          "retDesc": "获取成功!",
     *          "retValue": {
     *               名称                     类型                                                      说明
     * status                    constant                             返回结果状态值， 成功返回0。
     * location            lat                                     纬度坐标
     * lng                                     经度坐标
     * formatted_address    结构化地址信息
     * business            所在商圈信息，如 "人民大学,中关村,苏州街"
     * city                                     城市名
     * district                             区县名
     * addressComponent    province                             省名
     * street                                     街道名
     * street_number                             街道门牌号
     * pois（周边poi数组）     addr                                     地址信息
     * cp                                     数据来源
     * distance                             离坐标点距离
     * name                                     poi名称
     * poiType                                     poi类型，如’ 办公大厦,商务大厦’
     * point                                     poi坐标{x,y}
     * tel                                     电话
     * uid                                     poi唯一标识
     * zip                                     邮编
     *         }
     *     }
     * @status 1表为收藏,0表收藏
     * @apiError retCode=1为返回数据错误.
     *
     */
    function peripheral()
    {
        //接口权限校验
        verificationToken();

        $user_id = I("uid");
        $lng = I("get.lng", "113.65");
        $lat = I("get.lat", "34.76");


        $where['user_id'] = $user_id;
        $where['address_type'] = 1;
        $common_address = M('common_address');


        //根据user_id查找db_common_address中的poi_uid
        $user_address = $common_address->where($where)->getField("poi_uid", true);


        $ak = 'OkM4ci06ibVrimvizgsIWv0sjASIa7BK';
        $location = "$lat" . ",$lng";
        $url = "http://api.map.baidu.com/geocoder/v2/?ak=$ak&location=$location&output=json&pois=1";

        $json = file_get_contents($url);
        $data = json_decode($json, true);

        //把$data["result"]["location"]["lng"]转为$data["result"]["location"]["lon"]
        $data["result"]["location"]["lon"] = $data["result"]["location"]["lng"];
        //删掉之前的$data["result"]["location"]["lng"]
        unset($data["result"]["location"]["lng"]);

        if ($user_address) {
            foreach ($user_address as $k => $v) {
                foreach ($data["result"]['pois'] as $k2 => $v2) {
                    //若db_common_address中的poi_uid和周边的pois中的uid相等,则增加status为1,否则为0
                    if ($v == $v2["uid"]) {
                        $data["result"]['pois'][$k2]["status"] = 1;
                    } else {
                        $data["result"]['pois'][$k2]["status"] = 0;
                    }
                }
            }
        } else {
            foreach ($data["result"]['pois'] as $k2 => $v2) {
                $data["result"]['pois'][$k2]["status"] = 0;
            }
        }
        // die;
        return RET(0, "成功", $data);
    }

    /*
     * @api {get} delperipheral/uid/:uid/token/:token/poi_uid/:poi_uid/  根据uid和poi_uid取消收藏
     * @apiName 根据uid和poi_uid取消收藏
     * @apiGroup pt

     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} poi_uid 用户收藏地址的唯一标识.
     * @apiError retCode=1为返回数据错误.
     */
    function delperipheral()
    {
        //接口权限校验
        verificationToken();


        $common_address = M('common_address');

        $ret = $common_address->where(array('poi_uid' => I('poi_uid'), 'user_id' => I('uid')))->delete();
        if ($ret) {
            return RET_NO_V(0, "取消成功！");
        } else {
            return RET_NO_V(1, "取消失败！");
        }
    }

    /**
     * @api {get} pk_order_detaill/uid/:uid/token/:token/  根据order_resmsm查询9个跑客的信息
     * @apiName 根据order_resmsm查询9个跑客的信息
     * @apiGroup pk
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     *
     * @apiSuccessExample 成功返回:
     *  HTTP/1.1 200 OK
     * {
     *     "retCode": 0,
     *     "retDesc": "获取成功!",
     *     "retValue": {
     *         "dispatch_name": 王师傅已接单 送往  //跑客师傅
     *         "reci_address" : 锦华双语幼儿园 //跑客师傅的送往地
     *         "business" :     祭城           //跑客所在商圈信息，如 "人民大学,中关村,二七万达"
     * }
     * }
     * @apiError retCode=1为返回数据错误.
     **/
    function  pk_order_detail()
    {
        //接口权限校验
        pnerificationToken();
        $dispatch = M('dispatch');
        $order_resmsm = M('order_resmsm');
        $order_data = $order_resmsm->order('order_time')->limit(9)->field('dispatch_id,order_data')->where('pay_status=1 AND status="2"')->select();

        $ak = 'OkM4ci06ibVrimvizgsIWv0sjASIa7BK';
        $data = array();
        foreach ($order_data as $k => $v) {
            $dispatch_id = $v["dispatch_id"];
            $data[$k]["order_data"] = json_decode($v["order_data"], true);
           // dump($data[$k]["order_data"]);
            //获取跑客起始地
            $message[$k]["send_address"] = $data[$k]["order_data"]["send_address"] . $data[$k]["order_data"]["send_address_floor"];
            $lat = $data[$k]["order_data"]["send_latit"];
            $lng = $data[$k]["order_data"]["send_longit"];
            //获取跑客名字
            $message[$k]["dispatch_name"] = $dispatch->where("dispatch_id = $dispatch_id")->getField('dispatch_name');

            //根据名字截取姓氏 :王小波 变为 王师傅已接单 送往
//            $message[$k]["dispatch_name"] = $message[$k]["order_name2"][0]["dispatch_name"];
            $message[$k]["dispatch_name"] = substr($message[$k]["dispatch_name"], 0, 3) . "师傅已接单  ";

            //获取跑客周围的一个business点
            $location = "$lat" . ",$lng";
            $url = "http://api.map.baidu.com/geocoder/v2/?ak=$ak&location=$location&output=json&pois=1";
            $json = file_get_contents($url);
            $data = json_decode($json, true);
//            dump($data);
            $message[$k]["data"] = $data;
            $message[$k]["business"] = $message[$k]["data"]["result"]["addressComponent"]["district"];
            unset($message[$k]["data"]);

            // unset($message[$k]["dispatch_id"]);

        }
//        dump($message);

        if ($message) {
            return RET(0, "成功！", $message);
            //return RET_NO_V(0, "成功！",$message);
        } else {
            return RET_NO_V(1, "失败！");
        }
    }


    /**
     * @api {get} serach_userinfo/uid/:uid/token/:token/mobile/:mobile  查询用户信息是否充值
     * @apiName 查询用户信息是否充值
     * @apiGroup pn
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} mobile 手机号
     *
     **/
    function serach_userinfo()
    {
        $app_users = M('app_users');
        $app_user_data = $app_users->where(array('mobile'=>I('mobile')))->field('user_name,points_value')->find();
        if($app_user_data){
            return RET(1, "成功！", $app_user_data);
        }else{
            return RET_NO_V(0, "抱歉，无此用户！");
        }
    }

    /**
     * @api {get} getPrizeAngle/uid/:uid/token/:token/set_id/:set_id  获得转盘抽奖的角度值
     * @apiName 获得转盘抽奖的角度值
     * @apiGroup pk
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} set_id  db_sys_set表主键id，固定为6
     * @apiSuccessExample 成功返回:
     *  HTTP/1.1 200 OK
     *     {
     *    "retCode": 1,
     *    "retDesc": "获得角度成功！",
     *    "retValue": {
     *    "angle": 172,
     *    "prize": "1元现金"
     *    }
     *    }
     **/
    function getPrizeAngle(){
        verificationToken();
        $uid = I('uid');
       // dump($uid);
        $sys_set_obj = M('sys_set')->where(array('set_id'=>I('set_id')))->find();
        if($sys_set_obj && $sys_set_obj['collection_cost']){
            $prize_arr = json_decode($sys_set_obj['collection_cost'], true);
            $angle = getAngle($prize_arr);
           // dump($angle);
            $result = integral_subtraction($uid);
           // dump($result);
            if($result=== false){
              //  echo "积分不够无法抽奖！";
                return RET_NO_V(0, "积分不够无法抽奖！");
            }else{
                if($result){
                    $data = record_data($angle);
                    if($data === 0){
                     //   echo "抽奖数据写入数据库失败！";
                        return RET_NO_V(0, "抽奖数据写入数据库失败！");;
                    }else{
                      //  echo "获得角度成功！";
                            return RET(1, "获得角度成功！", $angle);
                    }
                }
            }
           
        }else
            return RET_NO_V(0, "数据参数有误！");
    }
    /**
     * @api {get} createPrizeResult/uid/:uid/token/:token/set_id/:set_id/result/:result/angle/:angle/points/:points  中奖结果写入数据库
     * @apiName 中奖结果写入数据库
     * @apiGroup pk
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {Int} set_id  db_sys_set表主键id，固定为6
     * @apiParam {Int} prize_id  db_sys_set表 collection_cost字段中奖id
     * @apiParam {Int} points  用户消耗积分
     **/
    function createPrizeResult(){
//        verificationToken();
        $sys_set_obj = M('sys_set')->where(array('set_id'=>I('set_id')))->find();
        if($sys_set_obj && $sys_set_obj['collection_cost']){
            $prize_arr = json_decode($sys_set_obj['collection_cost'], true);
            $prize_result = $prize_arr[I('prize_id')]['prize'];
            $user_prize_db = M('user_prize');
            $data = array('prize_id'=>I('prize_id')
                            ,'user_id'=>I('uid')
                            ,'prize_angle'=>I('angle')
                            ,'prize_result'=>I('result')
                            ,'valid_end_time'=>date("Y-m-d H:i:s",strtotime("+1 month"))
                            ,'is_used'=>1
                            ,'prize_key'=>I('prize_key')
                            ,'add_time'=>date("Y-m-d H:i:s",time())
                            ,'remark'=>'积分抽奖'
                        );
            $add_ret = $user_prize_db->add($data);
            //用户积分减少
            $points_ret = 1;
            $points_msg_ret = 1;

            $points_value = C('order_points');
            if ($points_value > 0) {
                $points_ret = addPoints(array('user_id' => I('uid'), 'points_type' => 1, 'points_value' => $points_value, 'remark' => '订单积分奖励', 'from_id' => 0));
//                $points_msg_ret = create_user_message(I('uid'), '订单送积分成功', '订单' . '' . '已完成，奖励' . $points_value . '积分', '订单' . $results['order_number'] . '已完成，奖励' . $points_value . '积分');
            }

            //用户积分表增加负积分
            if($add_ret){
                return RET(1, "恭喜您中奖了");
            }else
                return RET_NO_V(0, "中奖信息有误");
        }else
            return RET_NO_V(0, "没有抽奖活动");
    }
    /**
     * @api {get} getPrizeList/uid/:uid/token/:token/  获取中奖用户列表
     * @apiName 获取中奖用户列表
     * @apiGroup pk
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *  HTTP/1.1 200 OK
     *      {
     *    "retCode": 1,
     *    "retDesc": "恭喜您中奖了",
     *    "retValue": [
     *    {
     *      "user_id": "5",
     *      "mobile": "15738364224",
     *      "prize_result": "大奖"
     *    }
     *    ]
     *    }
     **/
    function getPrizeList(){
        verificationToken();
        $user_prize_db = M('user_prize p');
        $user_prize = $user_prize_db->field('p.user_id,a.mobile,prize_result')->where("valid_end_time >='".date('Y-m-d H:i:s',time())."'")
                                    ->join('db_app_users a on a.user_id = p.user_id')->order("add_time desc")->limit(10)->select();
//       echo $user_prize_db->getLastSql();
//        dump($user_prize);
        
        if($user_prize){
            foreach($user_prize as $key => $value){
                //$mobile = $value["mobile"];
                $value["mobile"] = substr($value["mobile"],0,3).str_repeat("*",4).substr($value["mobile"],-4);
                $user_prize[$key]=$value;
            }
            //dump($user_prize);
            return RET(1, "恭喜您中奖了",$user_prize);
        }else
            return RET_NO_V(0, "目前没有人中奖");
    }


    function  testAngle(){
        $prize_arr = array(
            '0' => array('id'=>1,'min'=>1,'max'=>44,'prize'=>'iPhone6s 64G','v'=>20),
            '1' => array('id'=>2,'min'=>46,'max'=>89,'prize'=>'10元现金','v'=>1),
            '2' => array('id'=>3,'min'=>91,'max'=>134,'prize'=>'8888体验金','v'=>10),
            '3' => array('id'=>4,'min'=>136,'max'=>179,'prize'=>'1元现金','v'=>1),
            '4' => array('id'=>5,'min'=>181,'max'=>224,'prize'=>'888体验金','v'=>50),
            '5' => array('id'=>6,'min'=>226,'max'=>279,'prize'=>'100元代金券','v'=>10),
            '6' => array('id'=>7,'min'=>281,'max'=>324,'prize'=>'1万元现金','v'=>8),
            '7' => array('id'=>8,'min'=>326,'max'=>359,'prize'=>'5元现金','v'=>0)
        );
        $angle = getAngle($prize_arr);
        dump($angle);
    }
    //http://localhost/bnpt/index.php/api/v1/testCouponFive/uid/1/total_amount/40
    function testCouponFive(){

        dump(couponUse(I('uid'),I('total_amount')));
    }
    function testOneOrderSendCoupon(){
        dump(send_coupon(I('uid')));
    }
    //积分换优惠券
     /**
     * @api {get} value_voucher/uid/:uid/token/:token/inte/:inte  积分兑换优三元惠券
     * @apiName 积分换优惠券
     * @apiGroup pk
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiParam {String} inte  用户准备兑换的积分值(必须是100的倍数).
     * @apiSuccessExample 成功返回:
     *  HTTP/1.1 200 OK
     *      {
     *    "retCode": 1,
     *    "retDesc": "兑换成功",
     *    "retValue": [
     *    {
     *      "success":您已成功兑换三张3元优惠券
     *    }
     *    ]
     *    }
     **/
    function value_voucher(){
       verificationToken();
       $inte = intval(I('inte'));
       $uid = I('uid');
       $data = value_exchange($uid,$inte);
      // dump($data);
       if($data === 0){
           return RET_NO_V(0, "抱歉,您的积分不足");
       }elseif($data === false){
           return RET_NO_V(0, "抱歉,请输入为100倍数的积分.");
       }
       else{
           $value['success'] = "您已成功兑换".$data."张3元优惠券";
           //echo ($value['success']);
           return RET(1, "积分兑换成功",$value);
       }
       
    }
    //积分兑换显示页面
    
    /**
     * @api {get} value_voucher_view/uid/:uid/token/:token 积分兑换显示页面
     * @apiName 积分换优惠券
     * @apiGroup pk
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *  HTTP/1.1 200 OK
     *      {
     *    "retCode": 1,
     *    "retDesc": "兑换成功",
     *    "retValue": [
     *    {
     *      "integral":500,
     *      "describe":每100积分可兑换一张3元优惠券
     *    }
     *    ]
     *    }
     **/
    function value_voucher_view(){
        verificationToken();
        $app_users = M('app_users');
        $integral = $app_users->where(array('user_id'=>I('uid')))->getField("points_value");
        //dump($integral);
        $value = array('integral'=>$integral,
                        'describe' => '每100积分可兑换一张3元优惠券');
         return RET(1, "成功",$value);
    }

     /**
     * @api {get} member_level/uid/:uid/token/:token 会员成长值
     * @apiName 会员成长值
     * @apiGroup pk
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     * @apiSuccessExample 成功返回:
     *  HTTP/1.1 200 OK
     *      {
     *    "retCode": 1,
     *    "retDesc": "成功",
     *    "retValue": [
     *    {
     *      "integral":1,// 1,普通会员 2,中级会员 3,高级会员 4,黄金会员 5,铂金会员 
      *     "mobile" :13949036223 //手机号
     *      "describe":还需1成长值即可为铂金会员||恭喜您成为最高级别会员
     *    }
     *    ]
     *    }
     **/ 
   function  member_level(){
       verificationToken();
       $sql = "select user_level_id,growth_value,mobile from db_app_users where user_id = ".I('uid');
       $level = M()->query($sql);
       $level = $level[0];
       if(intval($level["growth_value"]) >= 3000){
           $level_value = array("user_level_id"=>$level["user_level_id"],
                                 "mobile"      =>$level["mobile"],
                                     "content"      =>"恭喜您成为顶级会员." );
         //  dump($level_value);
                return RET(1, "成功",$level_value);
       }else{
                switch($level["user_level_id"]){
                    case '1':
                      $level['value'] = 100 - $level["growth_value"];
                      $level['grow_level'] = "中级会员";
                      break;
                    case '2':
                      $level['value'] = 300 - $level["growth_value"]; 
                      $level['grow_level'] = "高级会员";
                      break;
                    case '3':
                      $level['value'] = 900 - $level["growth_value"];
                      $level['grow_level'] = "黄金会员";
                      break;
                    case '4':
                      $level['value'] = 1500 - $level["growth_value"];
                      $level['grow_level'] = "铂金会员";
                      break;
                    case '5':
                      $level['value'] = 3000 - $level["growth_value"]; 
                      $level['grow_level'] = "顶级会员";
                }
                $level_value = array("user_level_id"=>$level["user_level_id"],
                                      "mobile"      =>$level["mobile"],
                                     "content"      =>"还需".$level["value"]."成长值即可为".$level["grow_level"] );
               // dump($level_value);
                return RET(1, "成功",$level_value);
       }
   }
}

